简体   繁体   中英

Lumen base url is different in a Controller and a Job

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.

Naturally UrlGenerator class gets the base url off of a Request instance 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);
    }
}

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