Laravel Echo is a tool that makes it easy to work with WebSockets and broadcasting events in a Laravel application. When combined with Vue.js, you can create real-time, reactive applications. Here's a step-by-step guide on how to use Laravel Echo for broadcasting events with Vue.js:
Install Laravel Echo and Pusher:
Make sure you have Laravel Echo and a broadcasting service like Pusher installed. You can install these using Composer:
bashcomposer require pusher/pusher-php-server
Also, configure your .env
file with your Pusher credentials:
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
Install Laravel Echo and Vue.js:
Install Laravel Echo and Vue.js packages using npm:
bashnpm install --save laravel-echo pusher-js
Configure Laravel Echo:
In your resources/js/bootstrap.js
file, import and configure Laravel Echo. Replace the Pusher settings with your own:
javascriptimport 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,
});
Broadcast an Event in Laravel:
Create an event in Laravel that you want to broadcast. For example, let's say you have an event called SomeEvent
. Make sure it implements ShouldBroadcast
:
phpnamespace App\Events;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class SomeEvent implements ShouldBroadcast
{
use SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function broadcastOn()
{
return new Channel('some-channel');
}
}
Broadcast the Event:
In your controller or wherever you want to broadcast the event, use the event
function:
phpevent(new SomeEvent($data));
Listen for the Event in Vue Component:
In your Vue component, use Laravel Echo to listen for the event:
javascriptmounted() {
window.Echo.channel('some-channel')
.listen('SomeEvent', (event) => {
console.log('Received SomeEvent', event);
// Handle the event data as needed
});
}
Make sure you call this within a lifecycle hook like mounted()
.
Compile Assets:
After making changes to your JavaScript files, compile your assets:
bashnpm run dev
Run Laravel WebSocket Server:
Start the Laravel WebSocket server to handle the broadcasting:
bashphp artisan websockets:serve
Note: The websockets
package is required for this, and you can install it using:
bashcomposer require beyondcode/laravel-websockets
Run Laravel Application:
Run your Laravel application:
bashphp artisan serve
Now, when the event is broadcasted, your Vue component should receive it in real-time.
Make sure you have a working WebSocket server for Laravel. The laravel-websockets
package is used in this example, but you can choose other packages as well. Adjust the configurations accordingly based on the package you use.