DEV Community

ashrakt
ashrakt

Posted on

Laravel Real-time

What Are Notifications in Laravel?
Laravel notification is a way to send a message to your users. Think of it as a central hub for all your app's alerts. Instead of writing separate code for emails, text messages, or in-app alerts, Laravel gives you a single, clean way to handle them all. You write the message once, and Laravel sends it through whatever channels you choose.

Types of Notifications
Laravel has several built-in notification types, each for a different purpose:

  1. Mail Notifications:
    These send a standard email. They're perfect for important updates like a new invoice or a password reset link.

  2. Database Notifications:
    This type saves a record of the notification in your database. It's used for the notifications you see inside an app. Users can see their notification history and mark them as read.

  3. SMS Notifications:
    send text messages directly to a user's phone. This is perfect for things that need immediate attention, like verification codes (OTP). Laravel supports this through services like Vonage and Twilio.

  4. Slack Notifications:
    send messages to Slack channels or to team members directly. This is great for sending internal alerts, like error logs or important system updates, helping development teams stay informed.

  5. Broadcast Notifications: This is the key to real-time notifications. It sends the notification data to a service like Pusher or Laravel Echo. This allows a user's browser to get an instant alert without having to refresh the page. This is what makes real-time functionality possible.


*How to Send a Notification to an Admin When a New User Registers
*

I- Prepare the Database
First, you need a table to save the notifications. Use this command to create a migration file:

  • php artisan notifications:table

Then, run the migration to create the table named notifications in your database:
php artisan migrate

II- Make Your Admin Model Notifiable
By default, Laravel's User model is already notifiable. But if you have a separate Admin model, you need to add the Notifiable trait to it. This gives the Admin model the superpower to receive notifications.

III- Create the Notification class
Next, create the notification class that will define the content. This example will create a notification for when a new user signs up.

  • php artisan make:notification NewUserRegisteredNotification

Open the new file app/Notifications/NewUserRegisteredNotification.php.

`<?php

namespace App\Notifications;

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

class NewUserRegisteredNotification extends Notification
{
use Queueable;
public $user;

public function __construct($newUser)
{
    $this->user = $newUser;
}

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


// public function toMail(object $notifiable): MailMessage
// {
//     return (new MailMessage)
//         ->line('The introduction to the notification.')
//         ->action('Notification Action', url('/'))
//         ->line('Thank you for using our application!');
// }


public function toArray(object $notifiable): array
{
    return [
        "name"    => $this->user->name,
        "email"   => $this->user->email,
        "message" => "new user registered",
    ];
}
Enter fullscreen mode Exit fullscreen mode

}
`

__construct()
This function is the "constructor" of the class. You use it to pass any data that the notification needs before it's sent.

via(object $notifiable): array
This function determines the channels the notification will be sent through. It simply returns an array with the names of the channels you want to use, like mail, database, or slack.

toMail(object $notifiable): MailMessage
This function is specifically for email notifications. If the via() function returns mail, this function will be used to build the email message. Here, you define the subject, the body text, and any buttons that will appear in the email.

toArray(object $notifiable): array
This function is a generic way to convert the notification into an array. It's used by different channels, like database and broadcast, to either save the notification or send it as data.


We want to store this notification in the database, so we'll use the database channel and define the data to be stored.

IIII- controller

If you have just one admin to notify.
` public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:' . User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);

    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);

    event(new Registered($user));

    $admin = Admin::find(1);
    $admin->notify(new NewUserRegisteredNotification($user));

    Auth::login($user);

    return redirect(RouteServiceProvider::HOME);
}`
Enter fullscreen mode Exit fullscreen mode
  • register form

  • notifications table

you can use another way
Notification::send($admin, new NewUserRegisteredNotification($user));

Top comments (0)