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
- Create a new Laravel project using the Laravel installer or Composer.
composer create-project --prefer-dist laravel/laravel chat-app
- Change to the project directory.
cd chat-app
- Install Livewire using Composer.
composer require livewire/livewire
- Configure your database connection in the
.env
file.
Step 2: Setting Up Pusher
- Sign up for a free Pusher account at https://pusher.com/ and create a new app.
- Note down your Pusher app credentials, including the app ID, key, secret, and cluster.
- Install the Pusher PHP library using Composer.
composer require pusher/pusher-php-server
- 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
- Generate a new Livewire component called
Chat
.
php artisan make:livewire Chat
- Open the newly created
app/Http/Livewire/Chat.php
file and update therender
method to return the viewlivewire.chat
.
public function render()
{
return view('livewire.chat');
}
- 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>
- Back in the
Chat
component class, define themessages
andnewMessage
properties, and thesendMessage
method.
public $messages = [];
public $newMessage;
public function sendMessage()
{
array_push($this->messages, $this->newMessage);
$this->newMessage = '';
}
Step 4: Updating the Routes and Layout
- Open the
routes/web.php
file and add the following route to handle the chat component.
Route::get('/chat', Chat::class);
- 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
- Modify the `
sendMessagemethod in the
Chat` component to broadcast the message using Pusher.
public function sendMessage()
{
array_push($this->messages, $this->newMessage);
$this->newMessage = '';
event(new MessageSent($this->messages));
}
- Generate a new event called
MessageSent
.
php artisan make:event MessageSent
- Open the
app/Events/MessageSent.php
file and update thebroadcastOn
method to use thechat-channel
channel.
public function broadcastOn()
{
return new Channel('chat-channel');
}
- Open the
app/Providers/EventServiceProvider.php
file and register theMessageSent
event in the$listen
array.
protected $listen = [
MessageSent::class => [
//
],
];
Step 6: Listening for Messages in Real-Time
- Update the
boot
method in theApp\Providers\BroadcastServiceProvider.php
file to use the Pusher broadcaster.
public function boot()
{
Broadcast::routes(['middleware' => ['web', 'auth']]);
require base_path('routes/channels.php');
}
- 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;
});
- Open the
resources/js/bootstrap.js
file and uncomment theimport Echo from 'laravel-echo'
andwindow.Pusher
lines, then update theEcho
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
});
- Compile the assets using Laravel Mix.
npm install && npm run dev
Step 7: Testing the Chat Application
- Start the Laravel development server.
php artisan serve
- Visit
http://localhost:8000/chat
in your browser. - Open another browser window or a private/incognito window to simulate a different user.
- 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!