简体   繁体   中英

Laravel - Artisan gives wrong base url

My app/config/app.php has

'url' => 'http://dev.domain.com/something/somethingElse'

Then I have a function that can be called from the application and also from an artisan command. But URL::route('myRoute') returns different results. When called from the application it returns http://dev.domain.com/something/somethingElse/myRoute , but in the artisan command http://dev.domain.com/myRoute .

URL::to has same behaviour.

Note: I do not have any other app.php file defined for other environments that could overwrite the global one.

Any ideas why this happens ? Thanks!

A Laravel-generated URL consists of a number of parts:

  • Scheme: http:// , https:// , etc.
  • Host: dev.domain.com , localhost , etc.
  • Base: something/somethingElse (the subdirectory on the web server)
  • Tail: myRoute , (the Laravel route parameters)

These parts are then concatenated to form the URL.

Ultimately, Laravel generates the URL using the $_SERVER request variables. The function prepareBaseUrl() in Symfony\\Component\\HttpFoundation\\Request is what is ultimately used to determine the base part of the URL.

When you make a request through your web browser, the request goes to ~/public/index.php and the necessary $_SERVER variables are populated with the correct information for Laravel to populate the base part of the URL.

However, when you make the request using Artisan on the command line, the request goes to the ~/artisan script. This means that the $_SERVER variables are not populated in the same way and Laravel is not able to determine the base part of the URL; instead, it returns an empty string '' .

From what I can find, it doesn't look like there is any appetite from the Laravel team to enable the application to function out-of-the-box in a subdirectory, eg Bugfix: domain routing for subfolder .

I ended up working around it in the way described by @medowlock for my scripts that would be called from the command line, eg:

Config::get('app.url') . URL::route('route.name', ['parameter'=>'value'], false)

This concatenates the application URL set in the app/config/app.php and the relative URL route.

If you use Laravel 4.2, you can call the URL::forceRootUrl function to explicitly define what the root url of your laravel application is.

URL::forceRootUrl( Config::get('app.url') );

Calls to URL::to will use the URL define in your app config file after forcing the Root URL.

Unfortunately, this isn't available in Laravel 4.1 or Laravel 4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM