Introduction:
In this tutorial, we will guide you through the process of creating a real-time chat application using Laravel Livewire and Pusher. Laravel Livewire is a powerful library that allows you to build interactive UI components in Laravel, while Pusher provides real-time functionality through websockets. Combining these two technologies, we can create a chat application that updates in real-time without the need for page refreshing.

Prerequisites:
To follow this tutorial, you should have a basic understanding of Laravel, Livewire, and Pusher. You should also have a local development environment set up with Laravel installed. If you haven't done this yet, you can refer to the official Laravel documentation for guidance.

Step 1: Setting Up the Laravel Project

  1. Create a new Laravel project using the Laravel installer or Composer.
composer create-project --prefer-dist laravel/laravel chat-app
  1. Change to the project directory.
cd chat-app
  1. Install Livewire using Composer.
composer require livewire/livewire
  1. Configure your database connection in the .env file.

Step 2: Setting Up Pusher

  1. Sign up for a free Pusher account at https://pusher.com/ and create a new app.
  2. Note down your Pusher app credentials, including the app ID, key, secret, and cluster.
  3. Install the Pusher PHP library using Composer.
composer require pusher/pusher-php-server
  1. Update your .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=your-app-cluster

Step 3: Creating the Chat Component

  1. Generate a new Livewire component called Chat.
php artisan make:livewire Chat
  1. Open the newly created app/Http/Livewire/Chat.php file and update the render method to return the view livewire.chat.
public function render()
{
    return view('livewire.chat');
}
  1. Create the livewire/chat.blade.php view file and add the following code:
<div>
    <ul>
        @foreach ($messages as $message)
            <li>{{ $message }}</li>
        @endforeach
    </ul>

    <input type="text" wire:model="newMessage" wire:keydown.enter="sendMessage">
</div>
  1. Back in the Chat component class, define the messages and newMessage properties, and the sendMessage method.
public $messages = [];
public $newMessage;

public function sendMessage()
{
    array_push($this->messages, $this->newMessage);
    $this->newMessage = '';
}

Step 4: Updating the Routes and Layout

  1. Open the routes/web.php file and add the following route to handle the chat component.
Route::get('/chat', Chat::class);
  1. Create a new layout file called resources/views/layouts/app.blade.php with the following content:
<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
    <livewire:styles />
</head>
<body>
    <livewire:chat />
    <livewire:scripts />
</body>
</html>

Step 5: Broadcasting the Chat Messages

  1. Modify the `

sendMessagemethod in theChat` component to broadcast the message using Pusher.

public function sendMessage()
{
    array_push($this->messages, $this->newMessage);
    $this->newMessage = '';

    event(new MessageSent($this->messages));
}
  1. Generate a new event called MessageSent.
php artisan make:event MessageSent
  1. Open the app/Events/MessageSent.php file and update the broadcastOn method to use the chat-channel channel.
public function broadcastOn()
{
    return new Channel('chat-channel');
}
  1. Open the app/Providers/EventServiceProvider.php file and register the MessageSent event in the $listen array.
protected $listen = [
    MessageSent::class => [
        //
    ],
];

Step 6: Listening for Messages in Real-Time

  1. Update the boot method in the App\Providers\BroadcastServiceProvider.php file to use the Pusher broadcaster.
public function boot()
{
    Broadcast::routes(['middleware' => ['web', 'auth']]);

    require base_path('routes/channels.php');
}
  1. Create a new channel file called routes/channels.php and add the following code:
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('chat-channel', function ($user) {
    return true;
});
  1. Open the resources/js/bootstrap.js file and uncomment the import Echo from 'laravel-echo' and window.Pusher lines, then update the Echo instance to use your Pusher app credentials.
import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});
  1. Compile the assets using Laravel Mix.
npm install && npm run dev

Step 7: Testing the Chat Application

  1. Start the Laravel development server.
php artisan serve
  1. Visit http://localhost:8000/chat in your browser.
  2. Open another browser window or a private/incognito window to simulate a different user.
  3. Send messages in one window and see them appear in real-time in the other window.

Conclusion:
Congratulations! You have successfully built a real-time chat application using Laravel Livewire and Pusher. You learned how to set up Laravel Livewire, integrate Pusher for real-time communication, create Livewire components, and broadcast events using Pusher. With this foundation, you can further enhance the chat application by adding features like user authentication, message persistence, and message notifications. Happy coding!

Techie Mike
Techie Mike
Self-taught techie, with a passion for computers and all the cool things you can do with them. Techie Mike, B.Eng. B.Sc.
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Techie Mike - The IT guy in Thailand.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.