-
app/Events/StoryStatusUpdated.php
Open in GitHubuse App\Models\Story; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class StoryStatusUpdated implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public function __construct( protected Story $story, public string $status, ){} public function broadcastOn(): array { return [ new Channel('story.' . $this->story->id), ]; } }
-
app/Models/Story.php
Open in GitHubuse App\Events\StoryStatusUpdated; class Story extends BaseModel { // ... static function boot() { parent::boot(); static::updated(function($story) { if ($story->isDirty('status')) { StoryStatusUpdated::dispatch($story, $story->status); } }); } // ... }
-
resources/js/Pages/Stories/Show.vue
Open in GitHub<template> // ... </template> <script setup> // ... const props = defineProps({ story: Object, }) const story = ref(props.story); Echo .channel(`story.${props.story.id}`) .listen('StoryStatusUpdated', (e) => { fetch(`/api/stories/${props.story.id}`) .then(response => response.json()) .then(data => { story.value = data; }); }); </script>