Building a Chat System in Laravel (Realtime Messaging using WebSockets & Pusher)

Building a Chat System in Laravel (Realtime Messaging using WebSockets & Pusher)

Introduction

Real-time messaging is an essential feature in modern applications. In this tutorial, we will implement a real-time chat system in Laravel using WebSockets and Pusher.

Step 1: Install Laravel and Required Packages

composer create-project --prefer-dist laravel/laravel chat-app
cd chat-app
composer require pusher/pusher-php-server

Step 2: Configure Pusher

Update the .env file with your Pusher credentials:

PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=mt1

Step 3: Setup Broadcasting

Enable broadcasting in config/broadcasting.php:

'default' => env('BROADCAST_DRIVER', 'pusher')

Step 4: Create a Chat Model and Migration

php artisan make:model Chat -m

Define the schema in the migration file:

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

Run the migration:

php artisan migrate

Step 5: Create Chat Events

php artisan make:event MessageSent

Update the event class:

class MessageSent implements ShouldBroadcast
{
    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new Channel('chat');
    }
}

Step 6: Implement the Chat Controller

php artisan make:controller ChatController

Define the message sending method:

public function sendMessage(Request $request)
{
    $message = Chat::create([
        'user_id' => auth()->id(),
        'message' => $request->message,
    ]);
    
    broadcast(new MessageSent($message))->toOthers();
    return response()->json(['message' => $message]);
}

Step 7: Setup Frontend with JavaScript

<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script>
    var pusher = new Pusher("your-app-key", {
        cluster: "mt1"
    });
    
    var channel = pusher.subscribe("chat");
    channel.bind("MessageSent", function(data) {
        console.log("New message: ", data.message);
    });
</script>

Conclusion

By following these steps, you can implement a real-time chat system in Laravel using WebSockets and Pusher. This setup allows for smooth and efficient real-time communication between users.

© 2025 Developer Sahayak. All Rights Reserved.

0 Comments