automate jobs laravel 9

Laravel 9 – Queues and Jobs Tutorial with Examples

In this post we will learn how to automate queues and jobs in Laravel 9 for emails which runs tasks in the background as sending them manually takes a lot of time. On the other hand, sending emails or text messages with larger attachments takes even much more time. If you followed this laravel 9 queues and jobs tutorial with examples correctly you can easily automate the process using laravel queue the whole process in Laravel 9 with a few tweaks here and there. 

We will use the laravel queue in laravel 9 to collect the data about emails, send them after a delay timestamp set by us. Its settings and details get stored in the config/queue.php file. You will find some details about the configuration of each queue driver such as Database, Beanstalkd, Redis, Amazon SQS already added there. Once we are done, you will see the emails getting sent without taking any of your time or energy. 

For this example we are using the database queue driver to send emails, generally any of the above drivers can be used. Next we will set the mail configuration and queue in the .env file. To make that change we need to go to the .env configuration file and add or change our mail database configurations. 

See the example here specially see that we have set QUEUE_CONNECTION to database as we are using database to queue all our tasks including automating our emails:

QUEUE_CONNECTION=database

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_FROM_NAME='Username'
[email protected]
MAIL_PASSWORD=*************
MAIL_ENCRYPTION=tls

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sendmail
DB_USERNAME=root
DB_PASSWORD=root

Copy the following code piece and add it in your routes/web.php file to set the queue

 
<?php

Route::get('send-mail', [HomeController::class, 'sendMail']); 

Now we need to create HomeController using this command

 php artisan make:controller HomeController

Now go to HomeController and add sendMail() method in the class to dispatch the task.

 <?php

namespace App\Http\Controllers;

use App\Jobs\SendMailJob;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Send email.
     *
     * @return void
     */
    public function sendMail()
    {      $details['to'] = '[email protected]';
        $details['name'] = 'Receiver Name';
        $details['subject'] = 'Hello Laramatic';
        $details['message'] = 'Here goes all message body.';

        SendMailJob::dispatch($details);

        return response('Email sent successfully');
    }
} 

You can add the timestamp to delay each dispatch/email. We are using delay period of two minutes. Like send email after every two minutes.

SendMailJob::dispatch($details);
        ->delay(now()->addMinutes(2));

The next we are going to create database queue table follow this artisan command to do that:

php artisan queue:table

It will invoke database migration, so let’s run add the migration command to create jobs table in our database

php artisan migrate

Now all of our tasks have been queued so far in respective drivers. The next we will create a job to actually perform the task of dispatching queue.

Run this command:

php artisan make:job SendMailJob

This will create App/Jobs/SendMailJob.php file with same classname. Job has handle() method which will be called when class is instantiated. We will send mail in the job, so add the following line to do that.

<?php

namespace App\Jobs;

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

class SendMailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $details;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->details['to'])
             ->send(new SendMail($this->details));
    }
}

We need to create Mailable class to send emails. Use this artisan command for that

php artisan make:mail SendMail

Now, in the handle() method of the Mail/SendMail.php file, do not forget to include this command line.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    public $details;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('email.send_mail')
                ->subject($this->details['subject'])
                ->with('details', $this->details);
    }
}

You will notice with the variable data we are sending Laravel blade view. Therefore, we need to open directory resources/view and add a new blade file email/send_mail.blade.php. We can also add the view. Check it here to access the variable that we pass in the class instance. See the example here.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Welcome Email</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <h2 style="text-align: center;">Laramatic</h2>
    <p>Hello!{!! $details['name'] !!}</p>
    <br>
    <p>{!! $details['message'] !!}</p>
</body>
</html>

Until now, we are almost done with all the coding part to automate our task/email sending job. Finally we need to start the server. Just type this command for that:

php artisan server

Run this in your browser http://localhost:8000/send-mail to check it. If you have followed this tutorial thoroughly it’s unlikely to meet any errors. If there’s none you will get the response ‘Email Sent Successfully.’ You can also check the time delay in task table.

This way you can automate sending emails by creating queue and jobs using Laravel 9.