Building a Real Time Chat Application with Laravel - A Guide
Loading

Building a Real Time Chat Application with Laravel – A Guide

Building Chat Application with the Help of Laravel

In today’s time, every web application needs some form of real-time communication with its clients. Laravel offers a simple interface that makes it easy to build modern applications with real-time interactions. The best Laravel development companies provide an option to add WebSocket technology to the application through an event broadcasting system. This system, in turn, allows the hired dedicated Laravel developers to share the same event names between the server-side code and the client-side JavaScript application.

For many years now, Pusher has been the only option for the hired Laravel programmers when building a chat application. Larasocket is the brand new broadcasting solution that is being quickly adopted by Laravel development companies in India. 

One of the major benefits of Larasocket over Pusher is the kind of pricing it offers. With Larasocket, the Laravel development company pays only for what it uses. In fact, there is a free tier also available that can easily get small projects off the ground.

Getting Started

This article gives a brief introduction to how the backend side of the Laravel chat application can be built with Larasocket. The following code can be used to build a real-time chat room application.

In order to create a fresh Laravel application, use the following steps:

laravel new larasocket-chat --auth

Now, to turn on broadcasting for any Laravel application, the hired Laravel developer needs to go to config/app.php and uncomment:

App\Providers\BroadcastServiceProvider::class,

Setting up Larasocket

First and foremost, the Laravel developer needs to set up the Larasocket. The following steps are used to do so:

Step 1: Include the Broadcasting Driver

composer require larasocket/larasocket-driver

Step 2:Once this is done, the developer should add Larasocket as a broadcasting connection option. This is done by using the command: config/broadcasting.php

'larasocket' => [
    'driver' => 'larasocket',
    'token' => env('LARASOCKET_TOKEN'),
],

Step 3The next step is simple enough. The developer needs to head on to the website Larasocket.com and get a free token

Step 4:Once these steps are complete, you need to update your .env

BROADCAST_DRIVER=larasocket
LARASOCKET_TOKEN=token
MIX_LARASOCKET_TOKEN="${LARASOCKET_TOKEN}"

With this step, the backend is set up and is ready to start using Larasocket.

Models

Next, the hired Laravel development company can create for itself a Message model with a migration:

php artisan make:model Message -m

The developer can now update the generated create_messages_table migration to:

Schema::create('messages', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->text('message');
    $table->timestamps();
});

With this, the developer is done making database changes. Next, the tables can be migrated:

php artisan migrate

Now, the Message.php is updated to look like:

class Message extends Model
{
    protected $fillable = [
        'message'
    ];

    public function user() {
        return $this->belongsTo(User::class);
    }
}

at this stage, the developer can even add a messages eloquent relationship in User.php

public function messages() {
    return $this->hasMany(Message::class);
}

Controllers

Once the models are ready to go, the Laravel developer can simply add the endpoints required for the chat application to send and receive messages.

php artisan make:controllerMessageController

The next step is to update the MessageController:

class MessageController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return Message::with('user')->get();
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $message = $user->messages()->create([
            'message' => $request->input('message')
        ]);

        return [
            'message' => $message,
            'user' => $user,
        ];
    }
}

After this step, the new routes can be added to the web.php:

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::view('/', 'chat')->middleware('auth');
Route::resource('messages', 'MessageController')->only([
    'index',
    'store'
]);

How to build Laravel chat application?

Broadcasting

The final thing that needs to be done for this program to work is to set up the events of the company so that they are broadcasted when new messages are created.

php artisan make:eventMessageSentEvent

This is the event that will get dispatched to the listeners of the broadcast – in other words, the users of the app. It can be used to pass on real-time information to the clients who are listening. The following example is created assuming the web browser to be the client. However, an iOS or Android application can be used in its place as well.

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

    public $message;
    public $user;

/**
     * Create a new event instance.
     *
     *
@return void
     */
public function __construct(Message $message, User $user)
    {
        $this->message = $message;
        $this->user = $user;
    }

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

To Be Remembered: 

It is essential that the developer does not forget to add: implements ShouldBroadcast to the class signature. This is because on the events that implement the ShouldBroadcast will finally be dispatched to the broadcast driver by Laravel. 

The remaining public properties arefinally passed along as data. 

The hired Laravel developer can implement a lot more customization in this program to tailor it according to client specification. 

Back over in MessageController, the developer also needs to broadcast the new event in the store method:

public function store(Request $request)
{
    $user = Auth::user();

    $message = $user->messages()->create([
        'message' => $request->input('message')
    ]);    // send event to listeners
    broadcast(new MessageSentEvent($message, $user))->toOthers();

    return [
        'message' => $message,
        'user' => $user,
    ];
}

Since the application would only prefer to allow authenticated users to use the chat feature, the events should be broadcasted on the private chat channel. Laravel developers can help a business control access to private and presence channels by using the routes/channels.php.

In that file, the developer can simply add authentication logic for the new channel.

Broadcast::channel('chat', function () {
    return \Illuminate\Support\Facades\Auth::check();
});

With this, the backend procedure is complete and the Laravel development company can proceed to building the UI for the business app.