To use Laravel Echo with ReactJS for real-time notifications, you'll need to follow a series of steps. Laravel Echo is a library that makes it easy to work with WebSockets and broadcast events in real-time. Here's a general guide on how to set up Laravel Echo with ReactJS:
First, make sure you have Laravel Echo and the broadcasting system installed in your Laravel project. This usually involves configuring a broadcasting driver like Pusher, Redis, or another supported driver.
Update your .env
file with the necessary broadcasting configuration. For example, if you are using Pusher, you might have something like this:
envBROADCAST_DRIVER=pusher PUSHER_APP_ID=your-app-id PUSHER_APP_KEY=your-app-key PUSHER_APP_SECRET=your-app-secret PUSHER_APP_CLUSTER=your-app-cluster
Set up event broadcasting. Create an event (e.g., NotificationEvent
) that you want to broadcast. In the event class, make sure to implement the ShouldBroadcast
interface.
phpuse Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NotificationEvent implements ShouldBroadcast
{
// Your event code here
}
Install Laravel Echo using npm:
bashnpm install --save laravel-echo pusher-js
In your bootstrap.js
file, configure Laravel Echo to use the broadcasting service you've set up:
javascriptimport Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
Make sure your .env
file contains the necessary MIX_PUSHER_APP_KEY
and MIX_PUSHER_APP_CLUSTER
values.
Wherever you want to broadcast the event (e.g., in a controller, a job, etc.), use the event
function:
phpevent(new NotificationEvent($data));
Install the necessary packages:
bashnpm install --save laravel-echo react-laravel-echo
In your ReactJS component, configure Laravel Echo to listen for the event:
jsximport React, { useEffect } from 'react';
import Echo from 'laravel-echo';
import LaravelEcho from 'react-laravel-echo';
const YourComponent = () => {
useEffect(() => {
const echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
});
echo.channel('your-channel-name').notification((notification) => {
// Handle the incoming notification
console.log('New Notification:', notification);
});
return () => {
// Clean up the Echo instance if needed
echo.disconnect();
};
}, []);
return (
// Your component code here
);
};
export default LaravelEcho(YourComponent);
Replace 'your-channel-name'
with the channel you've configured in your Laravel application.
That's it! With these steps, you should have Laravel Echo set up with ReactJS for real-time notifications. Adjust the code according to your specific requirements and application structure.