Create a re-useable Mailing Code in Laravel

Create a re-useable Mailing Code in Laravel

Hi there! In today’s posting, I would like to share with you guys how to create a Laravel Mailing reusable code.

What I mean here is not the php artisan make:mail. But the Mail::to Syntax.

I’m building one mechanism in my application to send the reminder email to all of our targeted users. There are two ways to send to them. One is done manually (by clicking a button and then sending the email), second is done automatically (by using Laravel Scheduler)

The problem I faced was a lot of Mail::to syntax logic that I needed to code. The full code is like this,

Mail::to($user->email)
->send(new SendFirstReminder($user->name, $user->email));

It took me nearly 20 seconds to code it (I’m a slow typer)!

And there are a few places where I need to put the code. Such as Controller, and Console.

That’s when I started to think. what if I need to use that mail code again?

So I need to spend another 20 seconds again? Of course, I don’t want to do that again.

So what happened is, that I created a custom Services Class. I named it as EmailReminder. In this class where I gather all the reminder emails. Everything is in one place.

Then I use the static method to make it more readable.

As you can see in this image, after I created the EmailReminder services, I can call it wherever I want without spending 20 seconds to code it. It can be reused in all places.

I just need to call it statically and then it will work like usual. But it is shortened and more readable (at least from my point of view)

Later I will create another post on how I created a reusable Local Scope logic for my application.

If you have other suggestions, comment below. I’d love to hear about your code strategy.

Leave a Reply

Your email address will not be published. Required fields are marked *