Andrew
Andrew

Reputation: 218

Changing the app url inside a Laravel 4.2 Artisan command

I run a multi-tenant site built in Laravel 4.2. In the App config, I'm aware that you can set a single base URL, e.g.

/*
|--------------------------------------------------------------------------
| 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://apples.local',

I've built an Artisan command to deliver scheduled emails to users, no matter which domain they access the site through. So the command needs to generate urls with a different domain, e.g. http://oranges.local.

In my command, I'm attempting to alter the app.url config variable before generating a URL, but it seems to have no affect:

Config::set('app.url', 'http://oranges.local');
$this->info('App URL: ' . Config::get('app.url'));
$this->info('Generated:' . URL::route('someRoute', ['foo', 'bar']));

Despite physically altering the config at runtime, this still always produces:

App URL: http://oranges.local
Generated: http://apples.local/foo/bar

The URL generator is completely ignoring the app config!

I know I can setup multiple environments and pass --env=oranges to Artisan, but in my use case this isn't really practical. I just want the ability to set the app url site-wide during runtime.

Any ideas?

Upvotes: 2

Views: 1846

Answers (2)

Andrew
Andrew

Reputation: 218

Ok, whoacowboy was right and the config is not being considered at all. What I've found is that the site's base URL (even in Artisan commands) seems to come all the way back from the Symphony Request object.

Therefore to change/spoof the domain inside Artisan, the following will work:

Request::instance()->headers->set('host', 'oranges.local');

It might be wise to revert the host name back again after you're done with the change, but at least in my use case, this has solved all my problems!

Upvotes: 2

whoacowboy
whoacowboy

Reputation: 7447

URL::route() calls $route->domain() which gets the domain from $route->action['domain']

/**
 * Get the domain defined for the route.
 *
 * @return string|null
 */
public function domain()
{
    return isset($this->action['domain']) ? $this->action['domain'] : null;
}

So it doesn't look like it is using Config::get('app.url') to set the url.

benJ seems to have a good idea. Why don't you manually write the URL?

$emailURL = Config::get('app.url') . '/foo/bar/' and call it a day.

Upvotes: 0

Related Questions