Lumen base url is different in a Controller and a Job

2.2k views Asked by At

I have a controller where URL::to('/') returns the base url of my website. However, when I use URL::to('/') in a job, it returns only a colon as a string (":").

class MyJob extends Job {
    public function handle() {
        Log::info(URL::to('/'));
    }
}

This returns "http://:"

class MyController extends Controller { {
    public function myMethod() {
        Log::info(URL::to('/'));
    }
}

This returns "http://my_domain.com"

I can't make sense of this. Should I just save the base url in the .env and use that?

I am using beanstalkd for queues.

1

There are 1 answers

1
peterm On BEST ANSWER

Naturally UrlGenerator class gets the base url off of a Requestinstance https://github.com/laravel/lumen-framework/blob/5.0/src/Routing/UrlGenerator.php#L289 which doesn't exist when you run your job worker in the CLI environment.

Therefore either store the base url in your .env file or pass it to your job when you dispatch it.

$app->get('/job', function() use ($app) {
    $app['Illuminate\Contracts\Bus\Dispatcher']->dispatch(new MyJob(url('/')));
});

MyJob.php

class MyJob extends Job
{
    private $base_url;

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

    public function handle()
    {
        app()['log']->info($this->base_url);
    }
}