Understanding Notifiable in Laravel

Laravel is a robust PHP framework known for its elegant syntax and developer-friendly tools. One of the framework’s features that often goes unnoticed is the Notifiable trait. This trait provides an efficient way to send notifications through various channels like email, SMS, or database without the need for complex configurations or repetitive code. In this article, we’ll explore what the Notifiable trait is, how it works, and how to use it effectively in your Laravel applicati

What is Notifiable in Laravel?

The Notifiable trait in Laravel is used by models to indicate that they can send notifications. It’s a simple yet powerful feature that allows you to trigger notifications when certain events or actions occur within your application, whether it’s a user registering, an order being placed, or a reminder being sent.

By using the Notifiable trait, you can handle notifications without manually writing out the logic for each notification channel. Laravel handles a lot of the heavy lifting for you, making it easy to send notifications in a clean, efficient way.

How Does Notifiable Work?

When you use the Notifiable trait in a model (commonly in the User model), the model gains the ability to send notifications. Laravel provides several built-in notification channels, such as:

  • Mail: Send notifications via email.
  • Database: Store notifications in a database table.
  • Broadcast: Broadcast notifications in real time using Laravel Echo.
  • SMS: Send notifications via SMS using third-party services like Nexmo.
  • Slack: Send notifications to Slack channels.
  • Custom Channels: Create your own notification channels.

To use the Notifiable trait, you simply need to include it in your model, typically the User model. Here’s an example:

use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    // Other model properties and methods
}

By adding Notifiable to the model, Laravel automatically includes methods like notify() and notifications(), which can be used to send and retrieve notifications.

Creating a Notification

To send a notification, you first need to create a custom notification class. Laravel provides the make:notification Artisan command to quickly generate a notification class.

php artisan make:notification NewUserRegistered

This will generate a new notification class in the app/Notifications directory. The generated class will look something like this:

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class NewUserRegistered extends Notification
{
    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('Welcome to Our Application!')
                    ->line('Thank you for registering with us.')
                    ->action('Visit Dashboard', url('/dashboard'))
                    ->line('We hope you enjoy using our application!');
    }
}

In this example, the notification will be sent via email. You can use different notification channels based on the method you return in the via function. Laravel supports many built-in channels, and you can even define custom channels if needed.

Sending a Notification

Once the notification is created, you can send it to a user (or any Notifiable model) using the notify() method. Here’s how you can send the NewUserRegistered notification to a user:

$user = User::find(1);
$user->notify(new NewUserRegistered());

This will send the email notification to the user. If you wanted to send a database notification or a Slack notification, you would just modify the via method and the corresponding method (like toDatabase or toSlack).

Storing Notifications in the Database

If you want to store notifications in the database so users can view them later, you can use Laravel’s built-in database channel. First, you need to create a notifications table:

php artisan notifications:table
php artisan migrate

Then, in your notification class, you can return database as one of the notification channels:

public function via($notifiable)
{
    return ['database'];
}

public function toDatabase($notifiable)
{
    return [
        'message' => 'A new user has registered on your platform.',
        'user_id' => $notifiable->id,
    ];
}

With this setup, the notification will be stored in the notifications table, and you can later retrieve it using the notifications() relationship on the user model:

$user = User::find(1);
$notifications = $user->notifications;




Marking Notifications as Read

Laravel also provides functionality for marking notifications as read. Once a user views a notification, you can mark it as read to differentiate it from unread notifications.

To mark a notification as read, you can use the markAsRead() method:

$user->notifications->first()->markAsRead();

You can also mark all of a user’s notifications as read:

$user->unreadNotifications->markAsRead();




By understanding and utilizing the Notifiable trait, you can build more engaging, interactive applications that keep users informed and connected with real-time updates.