Laravel: Get base url

Inigo picture Inigo · Apr 14, 2014 · Viewed 459.6k times · Source

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?

Answer

hannesvdvreken picture hannesvdvreken · Apr 14, 2014

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('/');
    }
}