Stop Refreshing! Laravel Echo Hooks for React and Vue
Overview
Real-time updates transform static web pages into living applications. While
Prerequisites
To follow this guide, you should have a baseline understanding of
Key Libraries & Tools
- Laravel Reverb: A first-party, high-performance WebSocketserver for Laravel applications.
- Laravel Echo: The JavaScript library that makes it painless to subscribe to channels and listen for events.
- echo-react / echo-vue: Specialized packages containing the new hooks (like
useEchoanduseEchoModel) for modern frontend frameworks. - Laravel Idea: A PhpStormplugin that accelerates development through advanced code generation.
Code Walkthrough
Setting up real-time features starts with the server-side configuration. Use the artisan command to pull in the necessary broadcasting scaffolding:
php artisan install:broadcasting
When prompted, select Reverb as the driver. This command installs the backend dependencies and the frontend packages, including echo-react or echo-vue.
Listening for Events
In a useEcho hook to subscribe to a private channel and react to a specific event. This replaces the old window.Echo.private().listen() syntax with a more declarative pattern:
useEcho('orders', (echo) => {
echo.private().listen('OrderStatusUpdated', (event) => {
console.log('Order Update:', event.order);
setOrder(event.order);
});
});
Synchronizing Models
The useEchoModel hook is even more specialized. It listens for standard BroadcastsEvents trait and define a broadcastOn method:
namespace App\Models;
use Illuminate\Database\Eloquent\BroadcastsEvents;
class User extends Authenticatable
{
use BroadcastsEvents;
public function broadcastOn($event)
{
return [new PrivateChannel('App.Models.User.' . $this->id)];
}
}
On the frontend, the hook tracks the specific model instance:
useEchoModel('App.Models.User', userId, {
updated: (event) => setUser(event.model),
});
Syntax Notes
When using event.order or event.model, your IDE provides full auto-completion. Notice the naming convention for private channels; App.Models.User) which must match exactly between the channels.php routes and the frontend hook call.
Practical Examples
- Live Notifications: Displaying a toast message when a user receives a new message without requiring a page poll.
- Order Tracking: Updating a progress bar or status badge on a dashboard as a package moves through shipping stages.
- Presence Indicators: Showing which team members are currently active on a shared document.
Tips & Gotchas
Always remember that private channels require authorization. If you see a 403 Forbidden error in your browser console, check routes/channels.php. You must define the authorization logic for every private channel. Additionally, ensure your queue worker is running (php artisan queue:work), as broadcasting events are dispatched to the queue by default to maintain application performance.
