Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Notification Channels in Laravel

Introduction

In Laravel, notifications are a powerful feature that allows you to send alerts or messages to users through various channels. Notification channels are the mediums through which these notifications are delivered. Laravel supports several channels out of the box including mail, database, broadcast, SMS (via Nexmo), and Slack.

Setting Up Notifications

To start using notifications in Laravel, you will need to create a notification class, which can be done using the Artisan command:

php artisan make:notification OrderShipped

This command creates a new notification class in the app/Notifications directory.

Defining Notification Channels

In your notification class, you can specify which channels you want to use to send notifications. Here’s how you can define the channels in your OrderShipped notification:

namespace App\Notifications;

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

class OrderShipped extends Notification
{
    use Queueable;

    public function via($notifiable)
    {
        return ['mail', 'database']; // Specify the channels
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting('Hello!')
                    ->line('Your order has been shipped!')
                    ->action('Track Order', url('/orders'))
                    ->line('Thank you for your purchase!');
    }

    public function toArray($notifiable)
    {
        return [
            'order_id' => $this->order->id,
            'status' => 'shipped',
        ];
    }
}
                

In this example, we defined that the notification will be sent via email and stored in the database.

Sending Notifications

To send the notification, you can use the notify method on the user model or any notifiable entity:

user()->notify(new OrderShipped($order));

Database Notifications

Laravel can store notifications in the database, allowing users to retrieve them later. To enable this, you need to create a migration for the notifications table:

php artisan notifications:table
php artisan migrate

After running the migration, you can access notifications in your application using:

auth()->user()->notifications;

Conclusion

Notification channels in Laravel provide a flexible way to send alerts through various platforms. By leveraging the built-in channels and creating custom ones, you can enhance user experience and keep your users informed. Be sure to explore different channels and find the best ones that suit your application's needs.