In this episode, we're working on getting new chat messages to show up instantly in our messages component when they're submitted. When we write something in the textarea and hit submit, we trigger a Livewire event called message.created
, passing along the ID of the new message we just saved.
The messages component is set up to listen for this event. Once it catches the event (and gets the message ID from the payload), we fetch the full message from the database — making sure to eagerly load the user so we don't trigger extra queries — and then push this message into our existing messages collection. Thanks to Laravel's collections, this is super straightforward, using the push
method to update the stack of messages in real time.
At the end, we test it out: typing a new message and hitting enter makes the message appear right away in our chat UI. We also notice a little scroll issue — new messages don’t automatically scroll to the bottom — but don’t worry, we’ll tackle that in the next episode!
So, the main idea here is setting up the real-time interface for posting messages by smartly using Livewire events and collections, laying the foundation for broadcasting messages to multiple users later.