loading...
Cover image for Laravel Queues

Laravel Queues

azibom profile image Mohammad Reza ・2 min read

So when we use queues
When you got many request that need to have a time consuming process you can solve this problem by using message queues

lets start

Create queue table

php artisan queue:table
php artisan migrate

Go to the QUEUE_CONNECTION and change it to some things like this

QUEUE_CONNECTION=database 

Create a job

php artisan make:job SendMail

Change your job like this

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $title;
    private $body;
    private $to;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($title, $body, $to)
    {
        $this->title = $title;
        $this->body = $body;
        $this->to = $to;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo "Start sending email".PHP_EOL;
        sleep(2);
        echo "Email sended to {$this->to}".PHP_EOL;
    }
}

Call dispatcher in you controller or anywhere you want

SendMail::dispatch("hi","how are you","alex@gmail.com");

Now you just need to start your queue with a command

php artisan queue:work

Or

php artisan queue:listen

And if you want to know what is the difference between those read this

"Alternatively, you may run the queue:listen command. When using the queue:listen command, you don't have to manually restart the worker when you want to reload your updated code or reset the application state; however, this command is not as efficient as queue:work:"

After that you should see sth like this

[2020-06-16 17:04:08][161] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:10][161] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:10][162] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:12][162] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:12][163] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:14][163] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:14][164] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:16][164] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:16][165] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:18][165] Processed:  App\Jobs\SendMail

And done

Feel free to ask any questions

Posted on by:

azibom profile

Mohammad Reza

@azibom

azibom ... bom ... bom

Discussion

markdown guide