V-K
V-K

Reputation: 1347

Running commands from Controller async

There is a migration task. User uploads file to the server, then it should be saved and migration command should be run async. The first path works well, there is an issue with the second part. I've tried to put all code to console command and run it with

Artisan::call('user:migrate', ['user_id' => $userId]);

or

Artisan::queue('user:migrate', ['user_id' => $userId]);

the script works, but not async, controller's function waits for the end. Also I've tried to create a Job and call it via:

$this->dispatch(new UserMigration($user));

and had the same result, script works but not async. Please help to realize how queues work and that approach is better for my task. I've not created any queue migrations and configuration, because need this step just async calling.

Upvotes: 1

Views: 2781

Answers (1)

Flame
Flame

Reputation: 7561

In order to run tasks asynchronous, the general idea in Laravel is to push jobs to a queue (database table for instance) and have a background process pick them up.

See https://laravel.com/docs/8.x/queues for information directly from the source.

You can start a queue worker using:

php artisan queue:work

Note that this is an ongoing process that doesn't stop unless it's told to do so. This means that any changes you make to the code, will only be reflected once you restart that queue worker. It is therefore important to run php artisan queue:restart (or kill and start the running task) when you deploy your code.

So now your queue worker is running, you can for instance queue an email to be sent (like upon registration), and your controller will respond immediately instead of having to wait for the email to be sent.

Most if not all info can be found in the link above. If you are going to have lots and lots of background tasks, take a look at Laravel Horizon.

Upvotes: 1

Related Questions