This blog post was written under the Pusher Guest Writer program.

Realtime message delivery status updates allow users to track the message without reloading the page. This paves a way to have better collaboration and conversation between friends and collaborators. It brings a dynamic feel to the application interface and improves usability.

Today, we will create a realtime message delivery status system using Laravel and Pusher. With the release of Echo, Laravel has provided an out of the box solution for implementing realtime data synchronisation using event broadcasting. It is simple and we can get started in a matter of minutes.

A basic understanding of Laravel and Vue is needed to follow this tutorial.

Setup an App on Pusher

We need to sign up on Pusher (it’s free) and create a new app.

Install Laravel, Pusher SDK and Echo

First, we will grab a fresh copy of Laravel:

laravel new message-delivery-status-laravel-pusher

This will install the latest version of the Laravel framework and download the necessary dependencies. Next, we will install the Pusher PHP SDK using Composer:

composer require pusher/pusher-php-server

Next, we will install the JavaScript dependencies:

npm install

Now, we need to install two Javascript libraries necessary for realtime event broadcasting: Laravel Echo and Pusher JS

npm install --save laravel-echo pusher-js

We require some form of user authentication mechanism to demonstrate the functionality. Let us use the default authentication scaffolding provided by Laravel:

php artisan make:auth

Configuration

First, we need to set the APP_ID, APP_KEY, APP_SECRET and APP_CLUSTER in the environment file. We can get these details in our Pusher app dashboard:

# .env

BROADCAST_DRIVER=pusher

PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster

Next, we need to create a fresh Echo instance in our applications’s JavaScript. We can do so at the bottom of our resources/assets/js/bootstrap.js file:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-app-key',
    cluster: 'ap2',
    encrypted: true
});

Our Application

We will create a realtime message delivery status in a chat box, similar to what Facebook does. The core feature is the realtime update of status for the messages. We will not cover anything relating to writing CRUD functionality using Laravel. We will concentrate on the code necessary for implementing the live commenting feature. The code is available on a Github repository for cloning and understanding purposes.

Migrations

Next, we need a conversations table where we can store all the messages for the conversation.

php artisan make:model Conversation -m

The conversations table will require the following fields:

  1. A field to store the message
  2. A field to link the message to the user that created it
  3. A field to store the status of the message

Below is the migration for our conversations table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateConversationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('conversations', function (Blueprint $table) {
            $table->increments('id');
            $table->text('message');
            $table->string('status');
            $table->unsignedInteger('user_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('conversations');
    }
}

Broadcasting New Messages

Whenever a new message is created, we need to fire an event which will be broadcast over Pusher to a specific private channel. For broadcasting an event, it should implement the ShouldBroadcast interface. Let us first create the NewMessage event:

php artisan make:event NewMessage

broadcastWith method

The event should implement a broadcastWith method. This method should return the array of data which the event should broadcast.

namespace App\Events;

use App\Conversation;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    private $conversation;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Conversation $conversation)
    {
        $this->conversation = $conversation;
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->conversation->id,
            'message' => $this->conversation->message,
            'status' => $this->conversation->status,
            'user' => [
                'name' => $this->conversation->user->name,
                'id' => $this->conversation->user->id,
            ],
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat');
    }
}

Next, we need to start our queue to actually listen for jobs and broadcast any events that are recorded. We can use the database queue listener on our local environment:

php artisan queue:listen

Broadcast the Event

Whenever a new message is created, we will broadcast the NewMessage event using the broadcast helper:

public function store()
{
    $conversation = Conversation::create([
        'message' => request('message'),
        'status' => 'Sent',
        'user_id' => auth()->user()->id
    ]);

    broadcast(new NewMessage($conversation))->toOthers();

    return $conversation->load('user');
}

If we do not use the toOthers method, then the event would also be broadcasted to the user who has created it. This would create a list of duplicate messages.

toOthers allows you to exclude the current user from the broadcast’s recipients.

Listening for New Messages on the Private Channel

Installation and configuration of Laravel Echo is a must before we can start listening to new messages. We have covered the process in detail in the above section of this article. Please go through it if you might have skipped it.

Echo.private('chat')
    .listen('NewMessage', (e) => {
        this.conversations.push(e);
    })

Broadcasting Status Updates

Whenever a new message is delivered to other users, we need to fire an event which will notify the sender that the message was delivered successfully. First, we will update the status of the message as delivered. Let us modify the above code in the Vue component to update the status, once the message is received.

Echo.private('chat')
    .listen('NewMessage', (e) => {
        this.conversations.push(e);
        axios.post('/conversations/'+ e.id +'/delivered');
    })

Now, let us update the status in the database and broadcast the MessageDelivered event:

class MessageDeliveredController extends Controller
{
    public function __invoke(Conversation $conversation)
    {
        $conversation->status = 'Delivered';
        $conversation->save();

        broadcast(new MessageDelivered($conversation));
    }
}

Following is the the event which is responsible for broadcasting the updated status data:

namespace App\Events;

use App\Conversation;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MessageDelivered implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    private $conversation;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Conversation $conversation)
    {
        $this->conversation = $conversation;
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->conversation->id,
            'message' => $this->conversation->message,
            'status' => $this->conversation->status,
            'user' => [
                'name' => $this->conversation->user->name,
                'id' => $this->conversation->user->id,
            ],
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat');
    }
}

Listening for Status Updates on the Private Channel

Next we find and update the conversation object on Vue side to update the status:

Echo.private('chat')
    .listen('MessageDelivered', (e) => {
        _.find(this.conversations, { 'id': e.id }).status = e.status;
    });

Authorization

Every private channel needs to be authenticated. Laravel Echo will automatically call the specified authentication route but we still need to write the authentication logic which will actually authorize the user to listen to a particular channel.

Authorization logic is written in the routes/channels.php. We will return true but you are free to write your own authorization code here:

Broadcast::channel('chat', function ($user) {
    return true;
});

Vue Component

That’s it! Now, whenever a new message is delivered, it will be broadcast and we can listen using our private channel to update the status in realtime.

Below is our Example component written using Vue.js

<script>
    export default {
        props: ['user'],
        data() {
            return {
                'message': '',
                'conversations': []
            }
        },
        mounted() {
            this.getConversations();
            this.listen();
        },
        methods: {
            sendMessage() {
                axios.post('/conversations', {message: this.message})
                    .then(response => this.conversations.push(response.data));
            },
            getConversations() {
                axios.get('/conversations').then((response) => this.conversations = response.data);  
            },
            listen() {
                Echo.private('chat')
                    .listen('NewMessage', (e) => {
                        this.conversations.push(e);
                        axios.post('/conversations/'+ e.id +'/delivered');
                    })
                    .listen('MessageDelivered', (e) => {
                        _.find(this.conversations, { 'id': e.id }).status = e.status;
                    });
            }
        }
    }
</script>

Below is the image demonstrating the workflow of our system:

Conclusion

In this article, we have covered how to create a realtime message delivery status using Laravel and Pusher. We have covered the configuration options necessary to get started, and the example above should help you fill in the gaps and give an overview of some of the other configuration options available to you.

The code is hosted on public Github repository. You can download it for educational purposes. How do you intend to use Laravel and Pusher? Can you think of any advanced use cases? What are they? Let us know in the comments!