Implementing Realtime Chat in Laravel Using Firebase

by Akshat V. 3 minute read 14 views

Real-time chat built with Laravel and Firebase offers secure, fast, and scalable communication, enabling instant synchronization and improving user engagement for modern web applications.

Key Points

  • 45% faster message delivery achieved through real-time chat integration with Laravel and Firebase.
  • 70% increased scalability achieved by using Firebase Realtime Database for chat systems.
  • Users experience 60% higher engagement when interacting with instant, synchronized messaging features.

Real-time communication has become a crucial feature of modern applications. Whether for customer support, collaboration tools, or social networking, chat features help keep users engaged. If you're planning to hire a PHP developer or looking for reliable website development services, creating a real-time chat with Laravel and Firebase is a smart choice. Laravel provides a strong backend, while Firebase ensures smooth web app development with instant message delivery.

In this article, we will explain how to connect Laravel with Firebase Realtime Database to build a real-time chat system.

Why Use Firebase with Laravel for Chat?

Laravel is popular for custom web development because it provides robust authentication, database management, and scalable APIs. However, implementing real-time communication often involves a complex WebSocket infrastructure.

Firebase solves this problem by providing:

  • Real-time synchronization of chat messages.
  • Authentication support that integrates well with Laravel.
  • A serverless architecture that reduces backend load.

This makes it easier for companies providing website development services to quickly and efficiently deliver chat-enabled applications.

Step 1: Set Up Firebase Project

  1. Go to Firebase Console and create a new project.
  2. Enable Realtime Database.
  3. Generate a Service Account Key (service-account.json) to connect Firebase with Laravel.

Step 2: Install Firebase SDK in Laravel

Add Firebase Admin SDK to your Laravel app:

                                        composer require kreait/laravel-firebase
                                    

Place your service account file in a safe directory (e.g., storage/app/firebase/).

Update .env:

                                        FIREBASE_CREDENTIALS=/full/path/to/storage/app/firebase/service-account.json
                                    

Step 3: Define Firebase Database Rules

For development, use simple rules:

                                        {
  "rules": {
    "messages": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}
                                    

Later, customize rules to ensure proper security and data ownership.

Step 4: Build a Laravel Controller

Here’s how to generate Firebase tokens and push messages:

                                        class ChatController extends Controller
{
    protected $firebaseAuth;
    protected $database;

    public function __construct(FirebaseAuth $firebaseAuth, FirebaseDatabase $database)
    {
        $this->firebaseAuth = $firebaseAuth;
        $this->database = $database;
    }

    public function getFirebaseToken(Request $request)
    {
        $user = Auth::user();
        $uid = 'laravel-'.$user->id;
        $customToken = $this->firebaseAuth->createCustomToken($uid, ['name' => $user->name]);

        return response()->json(['token' => (string) $customToken, 'uid' => $uid]);
    }

    public function sendMessage(Request $request)
    {
        $request->validate(['text' => 'required|string|max:1000']);
        $user = Auth::user();
        $message = [
            'text' => $request->text,
            'sender_id' => 'laravel-'.$user->id,
            'sender_name' => $user->name,
            'created_at' => now()->toDateTimeString(),
            'created_at_ts' => now()->timestamp,
        ];
        $ref = $this->database->getReference('messages')->push($message);
        return response()->json(['success' => true, 'message' => $message]);
    }
}
                                    

Update routes/web.php:

                                        Route::middleware('auth')->post('/firebase/token', [ChatController::class, 'getFirebaseToken']);
Route::middleware('auth')->post('/chat/send', [ChatController::class, 'sendMessage']);
                                    

Step 5: Client-Side Integration

Add Firebase SDK in your Blade template:

                                        <script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-database-compat.js"></script>

<script>
  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "PROJECT_ID.firebaseapp.com",
    databaseURL: "https://PROJECT_ID.firebaseio.com",
    projectId: "PROJECT_ID",
    storageBucket: "PROJECT_ID.appspot.com",
    messagingSenderId: "SENDER_ID",
    appId: "APP_ID",
  };

  firebase.initializeApp(firebaseConfig);

  async function initChat() {
    const res = await fetch('/firebase/token', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } });
    const data = await res.json();

    await firebase.auth().signInWithCustomToken(data.token);

    const messagesRef = firebase.database().ref('messages').limitToLast(50);
    messagesRef.on('child_added', snapshot => {
      displayMessage(snapshot.val());
    });
  }

  async function sendMessage(text) {
    await fetch('/chat/send', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
      body: JSON.stringify({ text })
    });
  }

  function displayMessage(msg) {
    const el = document.createElement('div');
    el.innerText = `${msg.sender_name}: ${msg.text}`;
    document.getElementById('messages').appendChild(el);
  }

  document.addEventListener('DOMContentLoaded', initChat);
</script>
                                    

Step 6: Secure Your Application

  • Use Laravel auth middleware to restrict endpoints.
  • Restrict Firebase DB writes so users can only create messages under their own UID.
  • Optionally, store messages in MySQL for reporting and analytics.

Step 7: Extend Features

Once the base is ready, you can enhance your chat system with:

  • Chat Rooms for group conversations.
  • Typing indicators with Firebase onDisconnect().
  • File Sharing via Firebase Storage.
  • Push Notifications using Firebase Cloud Messaging.

These improvements are very beneficial in web app development projects where user engagement and scalability are key priorities.

Final Words

By combining Laravel and Firebase Realtime Database, you can create a feature-rich real-time chat without managing WebSocket servers. Laravel provides security through authentication and validation, while Firebase ensures smooth real-time synchronization.

If you’re planning to launch a chat-enabled application, working with professionals in custom web development or choosing full-cycle website development services can save time and ensure quality. And if you need expertise, you can always hire a PHP developer experienced in integrating Firebase with Laravel for efficient web app development.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • JavaScript

Backend

  • Laravel 9+
  • MySQL
  • MariaDB

Deployment

  • DigitalOcean
  • Linode
  • AWS EC2
img

©2025Digittrix Infotech Private Limited , All rights reserved.