Laravel pusher real time chat application build with javaScript jQuery
In this tutorial we will build a live chat application using laravel 9.3 and php 8.1.5, javascript, jquery and pusher. After complete the chat app development we will see a live example how two users chat each other in real time. For building this app we have to follow bellow steps.
I'm using the following versions:
Laravel 9.3 ( You can use any other versions)
PHP 8.1.5
1. Install a fresh laravel project
2. Create pusher account and app
3. Configure .env with pusher app credentials (driver pusher)
4. Create event
5. Add Request Response and Event in web.php
6. Create chat page (welcome.php)
7. Link app.css and app.js file in chat page from resource
8. Install npm, pusher js and pusher server
9. Make changes in bootstrap.js
10. Chat js code in app.js
11. BroadcastServiceProvider
12. Test app
Step-1: Install a fresh laravel project
let's Install a fresh laravel project using composer or laravel installer.
/* using laravel installer*/
laravel new laravel-chat-application
/* using composer*/
composer create-project laravel/laravel laravel-chat-application
Step-2: Create pusher account and app
Create an account in pusher official website and create an app
Step-3: Configure .env with pusher app credentials (driver pusher)
Now we set pusher credentials in .env file and also change BROADCAST DRIVER log to pusher
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=your-pusher-cluster
Step-4: Ceate event and make changes in event file.
Now we have to create an event. You can make an event with any name by artisand command. Let's run bellow command to create an event with the name Message.
php artisan make:event Message
See our event file is successfully created in app\Events\Message.php which is located at app directory. Now open event file Message.php and make required changes. See the example code bellow class Message implements ShouldBroadcast and now we create a channel name like chat and also change the channel PrivateChannel to Channel in broascastOn() method. Keep in mind you are free to give a channel name. Next we have to create a method like broadcastAs() in which we return our event name message.
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class Message implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
public function __construct($username,$message)
{
$this->username = $username;
$this->message = $message;
}
public function broadcastOn()
{
return new Channel('chat');
}
public function broadcastAs()
{
return 'message';
}
}
Step-5: Add Request Response and Event in web.php
In this step we have to open web.php file and add request response and event.
Note: Don't forget to import Message and Request at the beginning of the file.
<?php
use App\Events\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::post('send-message',function (Request $request){
event(new Message($request->username, $request->message));
return ['success' => true];
});
Step-6: Create chat page welcome.php
It's time to create our chat page. Just create a blade file in views directory or you can convert your welcome page into chat page. I'm designing the welcome.blade.php file with the chat design markup. Bellow our chat markup code.
Note: Don't forget to add app.css and app.js also bootstrap and jquery link.
welcome.php
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
@vite(['resources/css/app.css' , 'resources/js/app.js'])
<title>Live Chat</title>
</head>
<body>
<div class="app">
<div class="row">
<div class="col-sm-6 offset-sm-3 my-2">
<input type="text" class="form-control" name="username" id="username" placeholder="Enter a user ..........">
</div>
<div class="col-sm-6 offset-sm-3">
<div class="box box-primary direct-chat direct-chat-primary">
<div class="box-body">
<div class="direct-chat-messages" id="messages"></div>
</div>
<div class="box-footer">
<form action="#" method="post" id="message_form">
<div class="input-group">
<input type="text" name="message" id="message" placeholder="Type Message ..." class="form-control">
<span class="input-group-btn">
<button type="submit" id="send_message" class="btn btn-primary btn-flat">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
</body>
</html>
Step-7: Add required css for chat page in app.css file
Now we need to add some css code in app.css for our chat design so that the markup looks much better. In app.css file paste the following code.
body{
margin-top:20px;
background:#eee;
}
.box {
position: relative;
border-radius: 3px;
background: #ffffff;
border-top: 3px solid #d2d6de;
margin-bottom: 20px;
width: 100%;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}
.box.box-primary {
border-top-color: #3c8dbc;
}
.box-body {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
padding: 10px;
}
.direct-chat .box-body {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
position: relative;
overflow-x: hidden;
padding: 0;
}
.direct-chat-messages {
padding: 10px;
height: 150px;
overflow: auto;
}
Step-8: Install npm, pusher js and pusher server
This part is the most important because we are going to install required packages for real time chat. At first we have to install npm secondly compile our js file thirdly pusher js and finally install pusher server. Let's run bellow command.
Note: While install pusher-php-server (4th command) must stop artisan server (php artisan serve) otherwise get errors.
npm install
npm run dev
npm install --save laravel-echo pusher-js
composer require pusher/pusher-php-server
Step-9: Make changes in bootstrap.js
Once Echo is installed, we are ready to create a fresh Echo instance in our application's JavaScript. We can do this is at the bottom of the resources/js/bootstrap.js
file that is included with the Laravel framework. By default, an example Echo configuration is already included in this file - we can simply uncomment it or add the following code bottom of the file.
resources/js/bootstrap.js
import _ from 'lodash';
window._ = _;
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
// window.Pusher = Pusher;
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: import.meta.env.VITE_PUSHER_APP_KEY,
// wsHost: import.meta.env.VITE_PUSHER_HOST ?? `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
// wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
// wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
// forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
// enabledTransports: ['ws', 'wss'],
// });
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true
});
Step-10: Chat js code in app.js
Well, we do everything except some mini task. Now we need to write our js code in resources/js/app.js. Simply add the bellow code in your app.js file.
resources/js/app.js
import './bootstrap';
$(document).ready(function(){
$(document).on('click','#send_message',function (e){
e.preventDefault();
let username = $('#username').val();
let message = $('#message').val();
if(username == '' || message == ''){
alert('Please enter both username and message')
return false;
}
$.ajax({
method:'post',
url:'/send-message',
data:{username:username, message:message},
success:function(res){
//
}
});
});
});
window.Echo.channel('chat')
.listen('.message',(e)=>{
$('#messages').append('<p><strong>'+e.username+'</strong>'+ ': ' + e.message+'</p>');
$('#message').val('');
});
Step-11: Finaly uncomment BroadcastServiceProvider from config/app.php
config/app.php
'providers' => [
App\Providers\BroadcastServiceProvider::class,
],
Step-12: Test app
Once you have uncommented and adjusted the Echo configuration according to your needs, you may compile your application's assets:
php artisan serve
npm run dev
You May Read Bellow Articles:
Laravel 9 live search data in a table using ajax.
How to send SMS in laravel 9 using Twilio SMS API-Webjourney
Laravel 9 pdf invoice generate and download with barryvdh dompdf
How to create multi language website by laravel 9
Laravel 10 multiple form validation on the same page-WebJourney
Multiple parameter pass through Route & URL in Laravel-WebJourney
Tags
Comments - 3
Nafis Chonchol
আমি যদি ডাটাবেস এর সাথে কানেক্ট করে কাজ করতে চাই , তাহলে শুধু Listiner Create করে কাজ করলেই তো হবে তাই না ?
Nov 3, 2022
WebJourney
Yes. Thanks
Dec 17, 2022