Article: Real-time Apps with Laravel 5.1 and Event Broadcasting

An excerpt from http://www.sitepoint.com/real-time-apps-laravel-5-1-event-broadcasting/, by Christopher Thomas

In Laravel 5.1, the framework includes functionality called broadcasting events that makes it easy to create real-time apps in PHP. With this new functionality, an app can publish events to various cloud-based real-time PubSub solutions, like Pusher, or to Redis.

In this article, we examine a simple todo app and turn it into a real-time app using Laravel’s broadcasting events.

Download and Install App

The easiest way to get started is to spin up an instance of Homestead Improved. If you don’t want to use Homestead Improved, you must have git and composer installed on your system.

We will put the starter code in a directory called todo-app by cloning a git repo.

git clone https://github.com/cwt137/l51-todo-app todo-app

After the cloning is finished, go into the todo-app directory. We need to install all the app dependencies by running the following command (depending on how your composer is set up, the command might be slightly different):

composer install

After all the dependencies are installed, we must set up our database.

php artisan migrate

Testing the Non Real-time App

This app is now functional, but without the real-time functionality provided by Laravel’s broadcasting events. Open up the homepage in two browsers and put them side by side so you can do a comparison. If you do not have two different browsers, you can use two browser windows.

Manipulate the todo list in the first browser window. Then do something in the second browser window. You will notice that the other browser window that you were not in does not update without hitting the refresh button. This is because there is no real-time functionality. Let’s add some.

Adding Real-time Capabilities to the App

Adding real-time capabilities will allow both browser windows to update their content without waiting for a hit of the refresh button.

In this example, we will define three Laravel event classes that get triggered at various times in our app. One event is the ItemCreated event that is triggered when a new item is created. The second event is the ItemUpdated event that is triggered when an item is updated (is marked completed or uncompleted). The last is the ItemDeleted event that is triggered when an item is removed from the todo list.

Broadcasting Events

To do broadcasting events, we will create a regular Laravel event, but we will implement an interface called ShouldBroadcast. If Laravel sees that an event class implements ShouldBroadcast it knows that it is a broadcasting event. This interface requires us to define a method inside our event class called broadcastOn. It should return an array of strings which are the channels that this event should be broadcasted on.

To create the event classes we need, run some artisan commands

php artisan make:event ItemCreated
php artisan make:event ItemUpdated
php artisan make:event ItemDeleted

Open up app/Events/ItemCreated.php and replace the contents with the code below:

<?php
 
namespace App\Events;
 
use App\Item;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class ItemCreated extends Event implements ShouldBroadcast
{
    use SerializesModels;
 
    public $id;
 
    /**
     * Create a new event instance.
     *
     * @param Item $item
     * @return void
     */
    public function __construct(Item $item)
    {
        $this->id = $item->id;
    }
 
    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['itemAction'];
    }
}

Laravel’s event system will serialize this object and broadcast it out on the real-time cloud system using the itemAction channel. The next couple of events are similar to the first.

Open up app/Events/ItemUpdated.php and replace the contents with the code below:

<?php
 
namespace App\Events;
 
use App\Item;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class ItemUpdated extends Event implements ShouldBroadcast
{
    use SerializesModels;
 
    public $id;
    public $isCompleted;
 
    /**
     * Create a new event instance.
     *
     * @param Item $item
     * @return void
     */
    public function __construct(Item $item)
    {
        $this->id = $item->id; 
        $this->isCompleted = (bool) $item->isCompleted;
    }
 
    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['itemAction'];
    }
}

Open up app/Events/ItemDeleted.php and replace the contents with the code below:

<?php
 
namespace App\Events;
 
use App\Item;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class ItemDeleted extends Event implements ShouldBroadcast
{
    use SerializesModels;
 
    public $id;
 
    /**
     * Create a new event instance.
     *
     * @param Item $item
     * @return void
     */
    public function __construct(Item $item)
    {
        $this->id = $item->id;
    }
 
    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['itemAction'];
    }
}

Continue reading this article on SitePoint!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.