Using Laravel's observer pattern with Vue.js for model events involves setting up Laravel observers to listen for specific model events and then broadcasting those events to a Vue.js front end using Laravel Echo and WebSocket. Here's a step-by-step guide:
Make sure you have Laravel Echo and Pusher installed. You can install them using the following commands:
bashcomposer require pusher/pusher-php-server npm install --save laravel-echo pusher-js
Update 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
Create a new observer using the following command:
bashphp artisan make:observer YourModelObserver --model=YourModel
This will generate a new observer class in the App/Observers
directory.
Inside your observer, implement the logic to broadcast the event to Pusher when a specific model event occurs. For example, in YourModelObserver.php
:
php<?php
namespace App\Observers;
use App\Models\YourModel;
use Illuminate\Support\Facades\Broadcast;
class YourModelObserver
{
/**
* Handle the YourModel "created" event.
*
* @param \App\Models\YourModel $yourModel
* @return void
*/
public function created(YourModel $yourModel)
{
Broadcast::channel('your-model-channel', function () {
return true; // You can implement channel authorization here if needed
});
// Broadcast the event to the channel
broadcast(new \App\Events\YourModelCreated($yourModel));
}
// Repeat the process for other events like updated, deleted, etc.
}
Create the event classes that correspond to the events you want to broadcast. For example, create a YourModelCreated
event:
bashphp artisan make:event YourModelCreated
In the generated YourModelCreated.php
file, you can define the event's broadcastOn method:
phppublic function broadcastOn()
{
return new Channel('your-model-channel');
}
Create a Vue component that listens for the broadcasted events. You can use Laravel Echo and Vue.js to achieve this. For example:
javascript// resources/js/components/YourModelComponent.vue
<template>
<div>
<p v-if="message">{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: "",
};
},
mounted() {
Echo.channel('your-model-channel')
.listen('YourModelCreated', (event) => {
this.message = 'Your model was created: ' + event.yourModel.name;
});
},
};
</script>
Include your Vue component in your Blade file or wherever you want to display the real-time updates.
Don't forget to compile your assets using:
bashnpm run dev
Run the Laravel Echo server to handle the WebSocket connections:
bashphp artisan echo:serve
Test the setup by creating, updating, or deleting a record in your model and check if the Vue component updates in real time.
Remember that this is a basic example, and you might need to adjust the code based on your specific requirements. Also, make sure your server environment supports WebSocket connections.