Have you open your app simultanuously in two different browsers to test it ?
Jan 22, 2023
8
Level 1
Livewire and Pusher
I think I am missing something really obvious but cannot see what I am over looking.
I am using Larvael 9, Livewire and Pusher.
I have a Form which allows the user to Post a comment which I am wanting to update for everyone in real time. Everything seems to be working as I can see the Post ID when I DD after the event but for some reasons I cannot get the posts to refresh automaticaly so it shows up without refreshing the brower.
I have the following code
Event
namespace App\Events;
use App\Models\Post;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $id;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Post $post)
{
//
$this->id = $post->id;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('posts');
}
}
The Livewire Post Component (To View All Posts)
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
class Posts extends Component
{
public $posts;
// Special Syntax: ['echo:{channel},{event}' => '{method}']
protected $listeners = ['echo:posts,PostCreated' => 'prependPost'];
public function mount()
{
$this->posts = Post::latest()->get();
}
public function UpdatePost($post)
{
dd($post); //Shows the Post ID
}
public function render()
{
return view('livewire.posts', [
$this->posts = Post::latest()->get()
]);
}
}
Post Form (Livewire Component)
namespace App\Http\Livewire;
use Livewire\Component;
use App\Events\PostCreated;
use Illuminate\Support\Facades\Auth;
class PostForm extends Component
{
public $body = '';
protected $rules = [
'body' => 'required',
];
public function storePost()
{
$this->validate();
$post = Auth::user()->posts()->create([
'body' => $this->body,
]);
//$this->emit('PostCreated', $post);
event(new PostCreated($post));
// broadcast(new PostCreated($posts));
$this->body = '';
}
public function render()
{
return view('livewire.post-form');
}
}
Any help would be appreciated :-)
Please or to participate in this conversation.