ChatGPT解决这个技术问题 Extra ChatGPT

Laravel: Get base URL

Simple question, but the answer seems quite hard to come by. In Codeigniter, I could load the URL helper and then simply do

echo base_url();

to get my site's URL. Is there an equivalent in Laravel?


h
hannesvdvreken

You can use the URL facade which lets you do calls to the URL generator

So you can do:

URL::to('/');

You can also use the application container:

$app->make('url')->to('/');
$app['url']->to('/');
App::make('url')->to('/');

Or inject the UrlGenerator:

<?php
namespace Vendor\Your\Class\Namespace;

use Illuminate\Routing\UrlGenerator;

class Classname
{
    protected $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }

    public function methodName()
    {
        $this->url->to('/');
    }
}

And despite its possible appearance from the example, this is relative to the Laravel's root path, so if you're installed in /something/ it'll make the right URL.
@deFreitas and #ceejayoz how to use URL::to with laravel localization?
@MubasharIqbal If I understood your question, {{URL::to('/my-page.html')}} at view and echo URL::to('/my-page.html'); at the code
nice handler, in my case: <a class="button is-primary" href="<?= URL::to('/'); ?>/atencion/reporte" target="_blank">, thanks!
A
Anye

Laravel < 5.2

echo url();

Laravel >= 5.2

echo url('/');

Could you expand this answer to include an explanation instead of just a code-snippet?
Exam: I have site in local: localhost/abc In Codeigniter: echo base_url(); => I get localhost/abc In Laravel: echo url(); => I get localhost/abc too.
Use this for an url with segmentation: url().'/'.\Request::segment(1).'/'.\Request::segment(2)
Note that this no longer works in 5.2: github.com/laravel/framework/issues/11479 You can use url('/') instead however
asset('/') seems better to me because it has trailing slash which is necessary in base href.
D
DrewT

For Laravel 5 I normally use:

<a href="{{ url('/path/uri') }}">Link Text</a>

I'm of the understanding that using the url() function is calling the same Facade as URL::to()


Note: if your website is served over https you can use the secure_url() function the same way, and this will produce an https link. Using url() on an https site will still produce an http link.
This one worked for me. Also useful to know the secure_url() syntax as well. Thanks.
I'm using Lumen 5.4. There url() generates a http or https link based on the protocol of the request. On the other hand secure_url() doesn't exist. Did this change in Laravel 5.4 too?
No, it's part of Larvel 5.4. I can't really comment because I have never used Lumen but the 5.4 Laravel documentation for secure_url() is available here: laravel.com/docs/5.4/helpers#method-secure-url
C
Community

Updates from 2018 Laravel release(5.7) documentation with some more url() functions and it's usage.

Question: To get the site's URL in Laravel? This is kind of a general question, so we can split it.

1. Accessing The Base URL

// Get the base URL.
echo url('');

// Get the app URL from configuration which we set in .env file.
echo config('app.url'); 

2. Accessing The Current URL

// Get the current URL without the query string.
echo url()->current();

// Get the current URL including the query string.
echo url()->full();

// Get the full URL for the previous request.
echo url()->previous();

3. URLs For Named Routes

// http://example.com/home
echo route('home');

4. URLs To Assets(Public)

// Get the URL to the assets, mostly the base url itself.
echo asset('');

5. File URLs

use Illuminate\Support\Facades\Storage;

$url = Storage::url('file.jpg'); // stored in /storage/app/public
echo url($url);

Each of these methods may also be accessed via the URL facade:

use Illuminate\Support\Facades\URL;

echo URL::to(''); // Base URL
echo URL::current(); // Current URL

How to call these Helper functions from blade Template(Views) with usage.

// http://example.com/login
{{ url('/login') }}

// http://example.com/css/app.css
{{ asset('css/app.css') }}

// http://example.com/login
{{ route('login') }}

// usage

<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">

<!-- Login link -->
<a class="nav-link" href="{{ route('login') }}">Login</a>

<!-- Login Post URL -->
<form method="POST" action="{{ url('/login') }}">

d
dan-klasson

To get it to work with non-pretty URLs I had to do:

asset('/');

To my need this is the best <base href="{{ asset('/') }}" />
Kudos to you! It fits just right in <base href="..."/> because of trailing slash
j
joshuamabina

This:

echo url('/');

And this:

echo asset('/');

both displayed the home url in my case :)


A
Akshay Khale

Laravel provides bunch of helper functions and for your requirement you can simply

use url() function of Laravel Helpers

but in case of Laravel 5.2 you will have to use url('/')

here is the list of all other helper functions of Laravel


@sambellerose and is you want to access inner folders/files you can do url('/css/style.css')
M
Mostafa Norzade

To just get the app url, that you configured you can use :

Config::get('app.url')

This definition is only used in Laravel cli. app.url it appears to be a fallback
Well anymore, env('APP_URL') would probably be the best option.
v
vikash singh

Check this -

<a href="{{url('/abc/xyz')}}">Go</a>

This is working for me and I hope it will work for you.


C
CptChaos

Another possibility: {{ URL::route('index') }}


Not sure why this got downvoted, as it actually works and no one gave the option as well?
Not my downvote but I'm guessing the reason is that you can't guarantee the naming of your root route to be "index" in every app.
X
X 47 48 - IR

There are multiple ways:

request()->getSchemeAndHttpHost()

url('/')

asset('')

$_SERVER['SERVER_NAME']


N
Niladri Banerjee - Uttarpara

You can also use URL::to('/') to display image in Laravel. Please see below:

<img src="{{URL::to('/')}}/images/{{ $post->image }}" height="100" weight="100"> 

Assume that, your image is stored under "public/images".


I
ITWitch

I used this and it worked for me in Laravel 5.3.18:

<?php echo URL::to('resources/assets/css/yourcssfile.css') ?>

IMPORTANT NOTE: This will only work when you have already removed "public" from your URL. To do this, you may check out this helpful tutorial.


E
Ethan

By the way, if your route has a name like:

Route::match(['get', 'post'], 'specialWay/edit', 'SpecialwayController@edit')->name('admin.spway.edit');

You can use the route() function like this:

<form method="post" action="{{route('admin.spway.edit')}}" class="form form-horizontal" id="form-spway-edit">

Other useful functions:

$uri = $request->path();
$url = $request->url();
$url = $request->fullUrl();
asset()
app_path();
// ...

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php


P
Paresh Barad

You can use facades or helper function as per following.

echo URL::to('/');
echo url();

Laravel using Symfony Component for Request, Laravel internal logic as per following.

namespace Symfony\Component\HttpFoundation;
/**
* {@inheritdoc}
*/
protected function prepareBaseUrl()
{
    $baseUrl = $this->server->get('SCRIPT_NAME');

    if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
        // assume mod_rewrite
        return rtrim(dirname($baseUrl), '/\\');
    }

    return $baseUrl;
}

A
Adeel Raza Azeemi

I found an other way to just get the base url to to display the value of environment variable APP_URL

env('APP_URL')

which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).


S
Soleil

you can get it from Request, at laravel 5

request()->getSchemeAndHttpHost();

M
Mostafa Norzade

I also used the base_path() function and it worked for me.