Optimising Laravel Mails
In my previous blog, I have discussed about basic functionality of sending mails to someone through your application. In this blog, I will be telling about some optimisation technique which can reduce the waiting time for the users.
As you have seen that while sending mail from controller, It takes a lot of time to process. So Laravel have provided us with a option to queue the sending of mails i.e sending the mails through background just like a cron job if you have heard about it.
It’s very easy to make any mail queueable. Let’s get started…
First of all you need to create migrations for jobs and failed jobs . It can be done by running :
php artisan queue:table
Now one simple way to make mails to run in queue is by just using queue method instead of send like this :
Mail::to($user->email)
->from('email-address')
->queue(new WelcomeMail($user))
One more thing which I forgot to mention in my previous blog is that you can also easily add cc and bcc to your mails by just adding cc and bcc methods like this :
Mail::to($user->email)
->from('email-address')
->cc('email-address')
->bcc('email-address')
->queue(new WelcomeMail($user))
After queuing the mail, If you will check jobs table in your db, you can find a job ready to be run. So for running the job just run :
php artisan queue:work
This will make the job to run in background and the mail will be sent if everything goes well. If in any case the job fails, you can check the reason of failure by going to failed-jobs table.
Laravel also provides a beautiful method to delay your mails for a certain amount of time. You just need to use the later method in place of queue method and later method accepts two parameter. One is the DateTime instance indicating when to send mail like next week, next hour or so and the second parameter is the mailable instance.
->later(now()->nextWeeks(1), new WelcomeMail($user));
So this will automatically send the mail after one week if the queue worker is running on your server.
Another way
One more way for making mails queueable is by using the ShouldQueue interface that is provided by Laravel queues.
Just implement ShouldQueue interface to the mailable class like this :
use Illuminate\Contracts\Queue\ShouldQueue;class WelcomeMail extends Mailable implements ShouldQueue{ //}
By using this you need not to use queue() method with Mail facade, send() method will also work.
So these were few simple tricks to optimise performance of your application for sending mails. Hope you like it and if you want in-depth explanation of queues and mailables, just hit the clap icon and I will be uploading more such simple content to make your life simple…..
Follow me for more such blogs…