Share this:

Real-time notifications have become an essential feature in modern web applications. It allows users to receive notifications instantly without having to refresh the page. Laravel 10, a popular PHP web framework, has made it easy to implement real-time notifications using Laravel Echo and Pusher.

In this article, we will go through the steps to implement real-time notifications with Laravel 10 Echo and Pusher. Before we begin, let’s quickly go through what Laravel Echo and Pusher are.

What is Laravel Echo?

Laravel Echo is a JavaScript library that makes it easy to subscribe to channels and listen for events broadcast by Laravel. It works with several broadcasting drivers, including Pusher.

What is Pusher?

Pusher is a real-time messaging service that allows you to send messages between your server and clients. It uses WebSocket technology to send messages instantly, providing real-time communication.

Now, let’s dive into the steps to implement real-time notifications with Laravel 10 Echo and Pusher.

Step 1: Set up a Pusher account and create a new app

The first step is to create a Pusher account and create a new app. You can sign up for a free account on their website. Once you have created an account, create a new app and make a note of the credentials.

Step 2: Install Laravel Echo and Pusher packages using Composer

Next, we need to install the Laravel Echo and Pusher packages using Composer. Open your terminal and run the following command:

composer require laravel/echo pusher-js

Step 3: Set up your Pusher credentials in the .env file

Once you have installed the packages, open your .env file and add the following variables:

PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=your-app-cluster

Make sure you replace the placeholders with your actual Pusher app credentials.

Step 4: Configure Laravel Echo in your app

Next, we need to configure Laravel Echo in our application. In the resources/js/bootstrap.js file, add the following code:

import Echo from 'laravel-echo'

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

This code sets up Laravel Echo to use Pusher as the broadcasting driver.

Step 5: Add the Laravel Echo service provider to the config/app.php file

Next, we need to add the Laravel Echo service provider to our application. Open the config/app.php file and add the following code under the ‘providers’ array:

'providers' => [
    // Other service providers...
    Laravel\Echo\EchoServiceProvider::class,
],

Step 6: Create a new notification in Laravel and broadcast it using Laravel Echo

Now that we have set up Laravel Echo, let’s create a new notification in Laravel and broadcast it using Laravel Echo. We can create a new notification using the following command:

php artisan make:notification YourNotification

This will create a new notification class under the app/Notifications directory.

Next, open your notification class and add the following code:

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

public function toDatabase($notifiable)
{
    return [
        'data' => 'Your notification data',
    ];
}

public function toBroadcast($notifiable)
{
    return new BroadcastMessage([
        'data' => 'Your notification data',
    ]);
}

The via() method returns the channels that the notification should be broadcast on.

In this case, we are broadcasting the notification on both the database and broadcast channels.

The toDatabase() method returns an array of data that should be stored in the database for this notification. In this example, we are simply returning a data array with a message.

The toBroadcast() method returns an instance of BroadcastMessage. This class provides a convenient way to specify the data that should be broadcasted to the clients. In this example, we are returning a new BroadcastMessage with a data array containing a message.

Step 7: Add a listener for the notification in your JavaScript code

Now that we have created our notification and set it up to be broadcasted using Laravel Echo, we need to listen for it in our JavaScript code. Open your JavaScript file and add the following code:

Echo.channel('notifications')
    .listen('.App\\Notifications\\YourNotification', (data) => {
        // Handle the notification data
    });

This code listens on the ‘notifications’ channel and listens for any events with the ‘.App\Notifications\YourNotification’ namespace. When a notification is received, it passes the data to the callback function.

Step 8: Trigger the notification from your PHP code

Now that we have set up our notification and our listener, we need to trigger the notification from our PHP code. We can do this by adding the following code:

$user->notify(new YourNotification());

This code triggers a new instance of our YourNotification class and sends it to the specified user.

Step 9: Trigger the notification from your JavaScript code

Finally, we can also trigger the notification from our JavaScript code. We can do this by making an AJAX request to our server. Open your JavaScript file and add the following code:

axios.post('/notifications', {
    message: 'Your notification message',
}).then(response => {
    // Handle the response
});

This code makes a POST request to the /notifications route on our server with a message parameter. Once the server receives the request, it triggers a new instance of our YourNotification class and broadcasts it using Laravel Echo.

And that’s it! You have successfully implemented real-time notifications with Laravel 10 Echo and Pusher. Real-time notifications are a powerful feature that can improve the user experience of your application. Laravel 10 makes it easy to implement real-time notifications using Laravel Echo and Pusher, allowing you to deliver instant updates to your users.

Share this:

Categorized in: