Real-time Notifications with Laravel and Redis

Real-time notifications are a common feature in web applications to provide instant alerts and updates to users without the need to refresh the page. In Laravel, you can easily integrate Redis to implement real-time notifications efficiently. Redis will be used as a queue to deliver notifications from the server to the client instantly.

Installing Redis and Laravel

To get started, install Redis on your server and install the predis/predis package in Laravel via Composer.

composer require predis/predis

Integrating Real-time Notifications

Configure Queue in Laravel

First, configure the queue in Laravel by adding the Redis information to the .env file.

QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Create an Event

Create an event in Laravel to send real-time notifications.

php artisan make:event NewNotificationEvent

Then, open the app/Events/NewNotificationEvent.php file and customize the event content.

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Queue\SerializesModels;

class NewNotificationEvent implements ShouldBroadcastNow
{
    use SerializesModels;

    public $message;

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

    public function broadcastOn()
    {
        return new Channel('notifications');
    }
}

Configure Broadcast Driver

Open the config/broadcasting.php file and use the redis driver to implement real-time notifications with Redis.

'connections' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
    ],
    // ...
],

Send Real-time Notification

When you need to send a real-time notification, use the event you just created in a controller or service provider.

use App\Events\NewNotificationEvent;

public function sendNotification()
{
    $message = 'You have a new notification!';
    event(new NewNotificationEvent($message));
}

Handle Real-time Notification on the Client

Finally, handle the real-time notification on the client using JavaScript and Laravel Echo. Make sure you have installed and configured Laravel Echo for your application.

// Connect to the 'notifications' channel
const channel = Echo.channel('notifications');

// Handle the event when receiving a real-time notification
channel.listen('.NewNotificationEvent', (notification) => {
    alert(notification.message);
});

 

Conclusion

Integrating Redis and Laravel allows you to easily deploy real-time notifications in your web application. When there is a new notification, the application will send it through Redis, and the client will receive the notification instantly without the need to refresh the page. This improves the user experience and enhances the interactivity of the application.