Laravel 10.please bring example of how I can use job (queue) in controller, so…
- User
Laravel 10.please bring example of how I can use job (queue) in controller, so controller waits for result of the job
- Assistant
Here's an example of using a job in a Laravel controller and waiting for the job to complete before continuing:
- Create a new job using the artisan command:
php artisan make:job ExampleJob- Open the
ExampleJobclass that was just created and add the following code to thehandlemethod:
public function handle() { // Perform some time-consuming task here sleep(10); // Store the result of the task in a variable $result = 'Task completed successfully!'; // Return the result to the controller return $result; }In this example, we're simulating a time-consuming task by sleeping for 10 seconds. You can replace this with your own code that performs a real-time task like sending an email or generating a report.
- In your controller method, dispatch the job and use the
dispatchSyncmethod to wait for the job to complete and get its result:
use App\Jobs\ExampleJob; use Illuminate\Support\Facades\Log; public function someMethod() { // Dispatch the job $job = new ExampleJob(); dispatch($job); // Wait for the job to complete and get its result $result = $job->dispatchSync(); // Log the result Log::info('Job result: ' . $result); // Do other stuff here // ... }In this example, we're dispatching the
ExampleJoband then using thedispatchSyncmethod to wait for the job to complete and get its result. We're also logging the result using Laravel'sLogfacade.Note that while waiting for the job to complete, the controller is blocked and will not respond to any other requests. This may not be ideal for a high-traffic application, so you should use this approach judiciously.