Building a real-time chat application has become a common requirement in modern web applications. With Laravel Livewire, creating dynamic and interactive user interfaces is simpler than ever. In this article, I will guide you through building a basic chat application using Livewire.
We'll set up Livewire components to send and receive messages in real-time.
Step-by-Step Guide: Building a Chat Application
Create a new Laravel project:
composer create-project laravel/laravel chat-app
cd chat-app
Install Livewire:
composer require livewire/livewire
Add Livewire's scripts and styles to your resources/views/layouts/app.blade.php file:
<head>
@livewireStyles
</head>
<body>
@livewireScripts
</body>
Configure your env file to set up the database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=chat_app
DB_USERNAME=root
DB_PASSWORD=
Run the migration for users:
php artisan migrate
Generate the model and migration for chat messages:
php artisan make:model Chat -m
Migration:
public function up()
{
Schema::create('chats', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->text('message');
$table->timestamps();
});
}
Run the migration:
php artisan migrate
Generate a Livewire component for the chat:
php artisan make:livewire Chat
Update app/Http/Livewire/Chat.php with the following logic:
namespace App\Http\Livewire;
use App\Models\Chat;
use Livewire\Component;
class Chat extends Component
{
public $messages;
public $message;
public function mount()
{
$this->messages = Chat::with('user')->latest()->take(20)->get();
}
public function sendMessage()
{
$this->validate([
'message' => 'required|string|max:255',
]);
Chat::create([
'user_id' => auth()->id(),
'message' => $this->message,
]);
$this->message = '';
$this->messages = Chat::with('user')->latest()->take(20)->get();
}
public function render()
{
return view('livewire.chat');
}
}
Create the corresponding view file resources/views/livewire/chat.blade.php
<div>
<div class="chat-messages">
@foreach($messages as $msg)
<p><strong>{{ $msg->user->name }}</strong>: {{ $msg->message }}</p>
@endforeach
</div>
<form wire:submit.prevent="sendMessage">
<input type="text" wire:model="message" placeholder="Type your message...">
<button type="submit">Send</button>
</form>
</div>
Add a route for the chat in routes/web.php
use App\Http\Livewire\Chat;
Route::get('/chat', Chat::class)->middleware('auth');
Make sure users are authenticated before accessing the chat.
Run your application:
php artisan serve
You might also like: