Laravel 5.4 #18 : Notifications

Laravel allows us to send notifications to users through different channels (SMS, mail, etc.). In this post, we will add notifications to our project, but will be a type of notifications that will be saved in the database and will be shown in a tab in the header.

Create the table in the database for the notifications, Laravel provide us one command to do this:

Execute it:

 

Create the notification file:

In this case, it will be a notification that will be launched when there is a new comment in the posts and will be sent to the creator of the post, saying him that a user has commented on one of his posts.

  • In the via function we indicated the type, we could add more than one.
  • In the toDatabase function we add the data that we want to access when we show the notification, we will see how now.

You can find more info in the documentation.

Open the  CommentsController.php  and modify the store function:

That line is the one that sends the notification to the specified user.

It could also be added that once a user comments on a post, when that post has a new comment, this user is notified.

 

Now, we will add the code to show the notifications. Add this code in the header when the user is logged in:

And we should see something like this:

 

It could easily be added with jQuery and Ajax that when you click on the Notifications button, the notifications in the list are marked as read.

 

-

– https://laravel.com/docs/5.4/notifications