Building Real-Time Applications with Laravel and Pusher
In today’s digital world, users expect real-time communication and interactivity in the applications they use. From chat applications to collaborative editing tools, real-time updates and notifications have become an essential part of modern web development. Laravel, a popular PHP framework, provides a solid foundation for building robust web applications, and when combined with Pusher, a powerful real-time communication platform, it becomes even more capable of delivering real-time features to users. In this blog post, we will explore how to integrate Pusher into Laravel applications to create real-time experiences that keep users engaged and informed.
Setting up a Laravel Project
To get started, we need to set up a new Laravel project. Assuming you have Laravel installed on your machine, open your terminal and run the following command:
sql Copy code $ laravel new real-time-app
This command will create a new Laravel project named “real-time-app” in the current directory.
Configuring Pusher
Next, we need to configure Pusher in our Laravel application. First, sign up for a free account on the Pusher website (https://pusher.com). Once you have an account, create a new app and take note of the app credentials (app_id, key, secret, cluster).
In your Laravel project, open the .env file and update the following lines with your Pusher credentials:
makefile PUSHER_APP_ID=your_app_id PUSHER_APP_KEY=your_app_key PUSHER_APP_SECRET=your_app_secret PUSHER_APP_CLUSTER=your_app_cluster
Broadcasting Events
To broadcast events in Laravel, we need to define the event classes and configure the broadcasting driver. Let’s create a new event class for demonstration purposes. Run the following command to generate the event class:
csharp $ php artisan make:event NewMessageEvent
This command will create a new event class named “NewMessageEvent” in the app/Events directory. Open the generated class and update it as follows:
php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Queue\SerializesModels; class NewMessageEvent implements ShouldBroadcastNow { use SerializesModels; public $message; public function __construct($message) { $this->message = $message; } public function broadcastOn() { return new Channel('chat'); } }
In this example, we’re broadcasting a “NewMessageEvent” on the “chat” channel. The event constructor accepts a message parameter, which will be broadcasted to the clients.
Next, open the config/broadcasting.php file and update the connections array as follows:
php 'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'useTLS' => true, ], ], ],
Listening to Events
To listen for events in your Laravel application, we need to set up a JavaScript client that can receive and handle the events. Let’s create a new JavaScript file to demonstrate this.
In your Laravel project, create a new file named resources/js/app.js and add the following code:
javascript 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, forceTLS: true, }); window.Echo.channel('chat').listen('NewMessageEvent', (e) => { console.log('New message:', e.message); });
This JavaScript code initializes the Echo client with the Pusher credentials from your Laravel application’s .env file. It then listens to the “chat” channel and handles the “NewMessageEvent” by logging the received message to the console.
To compile the JavaScript code, run the following command:
ruby $ npm install $ npm run dev
Implementing Real-Time Features
Real-Time Chat Application
Let’s implement a real-time chat application using Laravel and Pusher. First, we need to create the necessary routes, controllers, and views.
Create a new route in the routes/web.php file:
php use App\Http\Controllers\ChatController; Route::get('/chat', [ChatController::class, 'index'])->name('chat.index'); Route::post('/chat/send', [ChatController::class, 'send'])->name('chat.send');
Next, generate a new controller using the following command:
go $ php artisan make:controller ChatController
Open the ChatController class and update it as follows:
php namespace App\Http\Controllers; use App\Events\NewMessageEvent; use Illuminate\Http\Request; class ChatController extends Controller { public function index() { return view('chat'); } public function send(Request $request) { $message = $request->input('message'); event(new NewMessageEvent($message)); return response()->json(['success' => true]); } }
The index method returns the chat view, and the send method broadcasts the NewMessageEvent with the user’s message.
Create a new view file named resources/views/chat.blade.php and add the following HTML markup:
html <!DOCTYPE html> <html> <head> <title>Real-Time Chat Application</title> <link rel="stylesheet" href="{{ asset('css/app.css') }}"> </head> <body> <div class="container"> <h1>Real-Time Chat Application</h1> <div id="messages"></div> <form id="message-form"> <input type="text" id="message-input" placeholder="Type your message..."> <button type="submit">Send</button> </form> </div> <script src="{{ asset('js/app.js') }}"></script> <script> document.addEventListener('DOMContentLoaded', () => { const form = document.querySelector('#message-form'); const input = document.querySelector('#message-input'); const messages = document.querySelector('#messages'); form.addEventListener('submit', (e) => { e.preventDefault(); const message = input.value.trim(); if (message !== '') { axios.post('{{ route('chat.send') }}', { message }) .then(response => { input.value = ''; }) .catch(error => { console.log(error); }); } }); window.Echo.channel('chat').listen('NewMessageEvent', (e) => { const messageElement = document.createElement('p'); messageElement.textContent = e.message; messages.appendChild(messageElement); }); }); </script> </body> </html>
This view contains a form for sending messages, and a container to display the received messages. It also includes JavaScript code that sends messages via AJAX and appends the received messages to the container.
Real-Time Notifications
Real-time notifications are another common use case for real-time applications. Let’s see how to implement them in Laravel using Pusher.
First, create a new event class named NewNotificationEvent using the following command:
csharp $ php artisan make:event NewNotificationEvent
Open the NewNotificationEvent class and update it as follows:
php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Queue\SerializesModels; class NewNotificationEvent implements ShouldBroadcastNow { use SerializesModels; public $message; public function __construct($message) { $this->message = $message; } public function broadcastOn() { return new Channel('notifications'); } }
Similar to the chat example, this event class broadcasts a “NewNotificationEvent” on the “notifications” channel.
Next, open the app/Http/Controllers/NotificationController.php file and update it as follows:
php namespace App\Http\Controllers; use App\Events\NewNotificationEvent; use Illuminate\Http\Request; class NotificationController extends Controller { public function send(Request $request) { $message = $request->input('message'); event(new NewNotificationEvent($message)); return response()->json(['success' => true]); } }
Create a new route in the routes/web.php file to handle the notification sending:
php use App\Http\Controllers\NotificationController; Route::post('/notifications/send', [NotificationController::class, 'send'])->name('notifications.send');
To display the notifications, update the resources/views/chat.blade.php file with the following code:
html <!-- Existing code omitted for brevity --> <div id="notifications"></div> <script> // Existing code omitted for brevity window.Echo.channel('notifications').listen('NewNotificationEvent', (e) => { const notificationElement = document.createElement('p'); notificationElement.textContent = e.message; notifications.appendChild(notificationElement); }); </script>
This JavaScript code listens to the “notifications” channel and appends the received notifications to the container.
Conclusion
Congratulations! You have learned how to integrate Pusher into your Laravel application to create real-time experiences. We explored broadcasting events, listening to events using JavaScript, and implemented two real-time features: a chat application and real-time notifications. Laravel and Pusher together provide a powerful combination for building interactive and engaging real-time applications. Experiment with these concepts and explore further to unlock the full potential of real-time communication in your Laravel projects.
Table of Contents