Home » Php » Laravel: Change base URL?

Laravel: Change base URL?

Posted by: admin November 29, 2017 Leave a comment

Questions:

When I use secure_url() or asset(), it links to my site’s domain without “www”, i.e. “example.com”.

How can I change it to link to “www.example.com”?

Answers:

First change your application URL in the file config/app.php

'url' => 'http://www.example.com',

Then, make the URL generator use it. Add thoses lines of code to the file app/Providers/AppServiceProvider.php in the boot method:

\URL::forceRootUrl(\Config::get('app.url'));    
// And this if you wanna handle https URL scheme
// It's not usefull for http://www.example.com, it's just to make it more independant from the constant value
if (str_contains(\Config::get('app.url'), 'https://')) {
    \URL::forceScheme('https');
    //use \URL:forceSchema('https') if you use laravel < 5.4
}

That’s all folks.

Questions:
Answers:

Laravel uses the current domain when generating the secure_url and url(). However you can setup your defult url in app.php under config folder.

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://localhost',

Leave a Reply

Your email address will not be published. Required fields are marked *