Create Custom Laravel 8/9 Notifications with Jobs

Chimeremze Prevail Ejimadu
5 min readSep 28, 2022

--

Photo by Maxim Ilyahov on Unsplash

Sometime ago, I wanted to implement a quick notification system for a project I was working on, we know that laravel comes with it’s own notification system, but I need something custom to suit what I was building, so I decided to do a simple laravel notification feature with email jobs and this is what I came up with.

Here’s a simple scenario, User logs in, user takes some action (like comment on a post, follow an author, buys a product, subscribes to a service), we want to add it to his notification list and send him an email of that notification.

So let’s dive right in.

  1. Step 1: Install Laravel Project.
  2. Step 2: Setup Database.
  3. Step 3: Create Custom Notification Model.
  4. Step 4: Set up and run migration.
  5. Step 5: Create Jobs to handle notifications.
  6. Step 6: Create Route.
  7. Step 7: Create Email Blade.

Step 1: Step 1: Install Laravel Project

composer create-project --prefer-dist laravel/laravel projectName

Step 2: Setup Database

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=here your database nameDB_USERNAME=here database usernameDB_PASSWORD=here database password

Step 3: Create Custom Notification Model

Open the terminal inside the project folder or inside your IDE and run the command below. What this command does is to create a custom Notification.php file in App/Models, and create a migration file for it at app/database/migrations and finally create a controller name NotificationController.php at App/Http/Controllers.

php artisan make:model Notification -mc

Step 4: Set up and run migration

Next thing we have to do is to set up our migration file. Paste the following code in your notifications migration file. After you’ve done this, you can run the command to run migrations.

//This should be inside the Schema::create() method
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('notifiable_id')->nullable();
$table->unsignedInteger('type')->comment('1 for comment, 2 for following, 3 for invoice');
$table->boolean('read')->default(0);
$table->dateTime('read_at')->nullable();
$table->timestamps();

Here’s whats going on here, ‘user_id’ records the user who has the notification, If a user follows an author, a notification should be sent to the author that a new user followed him, so the author’s id should be the user id. We will see how it works in the controllers.
Then run your migrations with the command.

php artisan migrate

Step 5: Create Jobs to handle notifications

Now what we have to do is to create a Job that will handle creating and sending the notifications. You can do this in two ways: Create a separate job for each type of notification or One Job that will handle all types of notifications. I am going to use a single Job for this for the sake of this tutorial.

php artisan make:job Notify

This command creates a file Notify.php at App/Jobs. Now lets write our logic. Copy the code into your Notify.php.

<?phpnamespace App\Jobs;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class Notify implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $data = null;/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$notify = new Notification();
$notify->user_id = $this->data->user;
$notify->created_at = now();
if($this->data->type == 1){
// Since 1 represents 'comment' in out db, notifiable_id can be
// the id to the post under which user commented and user_id the author's id.
$notify->notifiable_id = $this->data->id;
$notify->type = 1;
} else if($this->data->type == 2){
// Since 2 represents 'following' in out db, notifiable_id can be
// the id of the user that followed, and user_id the person that was followed.
$notify->notifiable_id = $this->data->id;
$notify->type = 2;
} else {
// Since 3 represents 'invoice' in our db, notifiable_id can be the
// id of the product ordered and user_id is the id of the user who ordered it.
$notify->notifiable_id = $this->data->id;
$notify->type = 3;
}
$notify->save();
$user = User::find($notify->user_id);//Code to handle sending notification email to userMail::send('email.notify', ['user' => $user], function ($message) use ($user) {
$message->to($user->email);
//You can change the subject based on type
$message->subject('You have one new comment');
});
}
}

Step 6: Send Notification from different controllers

Now, here’s the sweet part, this is where you actually direct Laravel to create the notification. Let us make a notification after a user comments

$comment->save();
//After saving the comment
$data = [
'type' = 1,
'notifiable_id' => $post->id,
'user_id' => $post->author->id,
];
Notify::dispatch($data);
return redirect()->back()->with('success', 'You have commented successfully');

For one more example, let’s make a notification after a user follows another user.

$follow->save();
//After saving the follow
$data = [
'type' = 2,
'notifiable_id' => $the_user_who_followed_someone,
'user_id' => $the_user_that_was_followed,
];
Notify::dispatch($data);
return redirect()->back()->with('success', 'You are now following this user');

Remember, you have to set up your notify.blade.php in your resources/view/email folder to contain the email you want to send.
You might want to check your .env file and add your Queue Connection to whatever service you’re using, You can use database for a start

QUEUE_CONNECTION=database

To Process Jobs locally, you can run the command

php artisan artisan queue:work

Notifications are required in almost every application, especially which falls in the category of e-commerce, social media, or any noted digital product. There are different ways of implementing these, but it is determined by what you want to achieve, so something custom as this can work for you.

Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some clap 👏. And if you have any questions feel free to comment.

Thank you 🙏

Thanks a lot for reading till end 🙏 You can contact me in case if you need any assistance:
Email: prevailexcellent@gmail.com
Github: https://github.com/PrevailExcel
LinkedIn: https://www.linkedin.com/in/chimeremeze-prevail-ejimadu-3a3535219
Twitter: https://twitter.com/EjimaduPrevail

--

--

Chimeremze Prevail Ejimadu

Laravel Developer + Writer + Entrepreneur + Open source contributor + Founder + Open for projects & collaborations. Hit FOLLOW ⤵