Laravel 7 Notification Tutorial – Create Notification in Laravel

Last updated on by Digamber
Today is our lucky day, and We will know how to send a notification in laravel 7. Laravel mechanism is getting stronger day by day, and we all know it. The laravel notification system not just supports mail but it also goes smooth with the database, broadcasting, sms, slack, markdown etc.

Laravel Notification Example

Notifications can be seen as a short and straightforward message deliver to a user for giving vital info, events or to evoke action in the application. Preferably, notifications keep the existing users in the loop, and it boosts user engagement as well. This is also valuable from a user experience’s perspective.

Laravel offers noted features, and you can commence notification in laravel 7 by executing the artisan command.

Notifications are required in almost every application, especially which falls in the category of e-commerce, social media, or any noted digital product. Good news is you securely customize notification.

Install Laravel Project

With the consensus, let’s evoke the first step. In general, this step is the foundational step for installing the laravel application. Preferably, after this step, you can write code about creating a notification system in laravel.

composer create-project laravel/laravel laravel-notification-system --prefer-dist

After that, we make sure we enter inside the project directory with the following command.

cd laravel-notification-system

Set Up Database Connection

Before we move to our next step, invoke the MySQL database. It establishes the consensus between Laravel and MySQL.

Go to .env file and insert the given below code inside of it.

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

Create Notification Database Table

This step demonstrates how to create a database table for storing the notification in laravel.

Run the following command to produce notification table in the database.

php artisan notifications:table

In response to the execution of the above command, it created a notification file; file path is as follows database/migrations/timestamp_create_notifications_table.php

public function up()
{
    Schema::create('notifications', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('type');
        $table->morphs('notifiable');
        $table->text('data');
        $table->timestamp('read_at')->nullable();
        $table->timestamps();
    });
}

Later on, you can do subsequent things, such as:

  • Storing notification data in the database.
  • Running database queries to handle notifications.

Afterwards, execute the command to migrate the notification table.

php artisan migrate

Create Notification in Laravel 7

Thereafter, use the laravel artisan command to create the notification, execute the following command to create “Offers Notification”.

php artisan make:notification OffersNotification

Above command generated a new file and a folder, the path of the Notification file is as follows app/Notifications/OffersNotification.php.

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class OffersNotification extends Notification
{
    use Queueable;
    private $offerData;

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

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)                    
            ->name($this->offerData['name'])
            ->line($this->offerData['body'])
            ->action($this->offerData['offerText'], $this->offerData['offerUrl'])
            ->line($this->offerData['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'offer_id' => $this->offerData['offer_id']
        ];
    }
}

Define Notification Route

Define a route that helps to send a notification to a single user, place the following code in routes/web.php to create the route.

In general, the http method should be defined with Route method. Get is something that solves our problem here, pass route url name along with the controller class and sub-method of the controller.

Route::get('send-notification', 'NotificationController@sendOfferNotification');

Create Notification Controller

Ultimately, we create a controller by the name of OfferController. Run the below command to create a controller.

php artisan make:controller NotificationController

This controller will hold the core logic for sending notification. The notification mechanism we are developing is small compared to other functionalities. But it is good to go if you are just getting started.

Make this controller workable by assimilating the following code in app/Http/Controllers/NotificationController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\User;
use Notification;
use App\Notifications\OffersNotification;

class NotificationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    public function index()
    {
        return view('product');
    }
    
    public function sendOfferNotification() {
        $userSchema = User::first();
  
        $offerData = [
            'name' => 'BOGO',
            'body' => 'You received an offer.',
            'thanks' => 'Thank you',
            'offerText' => 'Check out the offer',
            'offerUrl' => url('/'),
            'offer_id' => 007
        ];
  
        Notification::send($userSchema, new OffersNotification($offerData));
   
        dd('Task completed!');
    }
}

Once you are done with everything, then you can run given below command to start the laravel app on the browser and send the test notifications.

php artisan serve

The notification system can be tested with the following path.

http://127.0.0.1:8000/send-notification

How to Send Notification

Do you know laravel notification system offers two methods to send notifications. You may opt either Notifiable trait or Notification facade. Preferably, in this tutorial, we will discuss the Notifiable trait.

Generically, the trait is a single method default work with App\User model. Often, used for sending a notification: notify, and it demands to receive a notification instance.

use App\Notifications\OffersNotification;


$userSchema->notify(new OffersNotification($offerData));

Here is the simplest way to receive a notification.

dd($userSchema->notifications);

Summary

Eventually, we have completed our work, and we propelled our comprehension of the notification system in laravel. In this tutorial, we saw how to work with laravel notification mechanism to notify a user about an important update. Altogether, we saw every foundational step to get along with this tutorial, i hope you liked this article. Have a good day.