How to create a Real-Time Chat using Laravel and Firebase

Real-time Laravel FCM chat
new web app icon
@section('scripts')
<script>
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("your publicVapidKey");
</script>
@endsection
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
class FCMController extends Controller
{
//
public function index(Request $req){
return "testing";
}
}
?>
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->longText('fcm_token')->nullable();
$table->rememberToken();
$table->timestamps();
});
public function index(Request $req){
$input = $req->all();

return response()->json($input);
}
Route::post('/save-token', 'FCMController@index');
@section('scripts')
<script>
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("BNi8WFY0HVBE2YvPXCfj7wDGbURGAh6rD57klttmetVL-PDYCnPNOgvUfC_RZquDF6uXjS5f78PXAcnFI9KuNTE");


function sendTokenToServer(fcm_token) {
const user_id = '{{auth()->user()->id}}';
//console.log($user_id);
axios.post('/api/save-token', {
fcm_token, user_id
})
.then(res => {
console.log(res);
})

}

function retreiveToken(){
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
// updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
//console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
//updateUIForPushPermissionRequired();
//etTokenSentToServer(false);
alert('You should allow notification!');
}
}).catch((err) => {
console.log(err.message);
// showToken('Error retrieving Instance ID token. ', err);
// setTokenSentToServer(false);
});
}
retreiveToken();
messaging.onTokenRefresh(()=>{
retreiveToken();


});

messaging.onMessage((payload)=>{
console.log('Message received');
console.log(payload);

location.reload();
});

</script>
@endsection
public function index(Request $req){
$input = $req->all();
$fcm_token = $input['fcm_token'];
$user_id = $input['user_id'];


$user = User::findOrFail($user_id);

$user->fcm_token = $fcm_token;
$user->save();
return response()->json([
'success'=>true,
'message'=>'User token updated successfully.'
]);
}
'providers' => [
// ...

LaravelFCM\FCMServiceProvider::class,
]
'aliases' => [
// ...
'FCM' => LaravelFCM\Facades\FCM::class,
'FCMGroup' => LaravelFCM\Facades\FCMGroup::class, // Optional
]
@section('content')
<style>
.chat-container {
display: flex;
flex-direction: column;
}

.chat {
border: 1px solid gray;
border-radius: 3px;
width: 50%;
padding: 0.5em;
}

.chat-left {
background-color: white;
align-self: flex-start;
}

.chat-right {
background-color: #3f9ae5;
align-self: flex-end;
}

.message-input-container {
position: fixed;
left: 0;
right: 0;
bottom: 0;
background-color: white;
border: 1px solid gray;
padding: 1em;


}
</style>
<div class="container" style="margin-bottom: 480px" >
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>

<div class="card-body">
<div class="chat-container">

<p class="chat chat-right">
<b>A :</b><br>
message1 </p>
<p class="chat chat-left">
<b>B :</b><br>
message 2
</p>



</div>
</div>
</div>
</div>
</div>
</div>
<div class="message-input-container">
<form action="" method="POST">
@csrf
<div class="form-group">
<label>Message</label>
<input type="text" name="message" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">SEND MESSAGE</button>
</div>
</form>
</div>
@endsection
chats section
new message section
Schema::create('chats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('sender_id');
$table->string('sender_name');
$table->longText('message');
$table->timestamps();
});
protected $fillable=[
'sender_id',
'sender_name',
'message'
];
public function createChat(Request $request)
{
$input = $request->all();
$message = $input['message'];
$chat = new Chat([
'sender_id' => auth()->user()->id,
'sender_name' => auth()->user()->name,
'message' => $message
]);

$chat->save();
return redirect()->back();

}
<div class="chat-container">
@if(count($chats)==0)
<p>There is no chat yet.</p>
@endif
@foreach($chats as $chat )
@if($chat->sender_id === auth()->user()->id)
<p class="chat chat-right">
<b>{{$chat->sender_name}} :</b><br>
{{$chat->message}} </p>
@else
<p class="chat chat-left">
<b>{{$chat->sender_name}} :</b><br>
{{$chat->message}}
</p>
@endif
@endforeach


</div>
Route::get('/home', 'HomeController@index')->name('home');

Route::post('/home','HomeController@createChat')->name('home.createChat');
private function broadcastMessage($senderName, $message)
{
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60 * 20);

$notificationBuilder = new PayloadNotificationBuilder('New message from : ' . $senderName);
$notificationBuilder->setBody($message)
->setSound('default')
->setClickAction('http://localhost:8000/home');

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData([
'sender_name' => $senderName,
'mesage' => $message
]);

$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();

$tokens = User::all()->pluck('fcm_token')->toArray();

$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);

return $downstreamResponse->numberSuccess();

}
public function createChat(Request $request)
{
$input = $request->all();
$message = $input['message'];
$chat = new Chat([
'sender_id' => auth()->user()->id,
'sender_name' => auth()->user()->name,
'message' => $message
]);

$this->broadcastMessage(auth()->user()->name,$message);

$chat->save();
return redirect()->back();

}
FCM_SERVER_KEY = your key
FCM_SENDER_ID = your id
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
var firebaseConfig = {
apiKey: "your key",
authDomain: "your app url",
databaseURL: "your app db url",
projectId: "your project id",
storageBucket: "your storage bucket",
messagingSenderId: "your message senderid",
appId: "your app id"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const {title, body} = payload.notification;
const notificationOptions = {
body,
};

return self.registration.showNotification(title,
notificationOptions);
});

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

6 Benefits Of Integrating ERP in eCommerce Business

#FailedAmericanSlogans Are Terrifying Mottos For Life Under Trump

How to create a form with HTML5

Java OOPs Concepts

Security Of Virtual Machines And Containers.

Scrum Master: How to run Scrum Meetings with a Team?

The so called “About me” — a simple intro

How to Write your own Flight Controller Software — Part 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hiran Lowe

Hiran Lowe

More from Medium

How to Create Custom 404 Error Page in Laravel?

Password and Confirm Password Validation in Laravel

Laravel Vs. Codeigniter: A Head to Head Comparison

Tests are important and here’s WHY!