Cover 21

Building a Real-Time Chat Application with Laravel and Pusher

Prerequisites:

To follow along with this tutorial, you should have a basic understanding of Laravel, PHP, and JavaScript. Familiarity with Vue.js, a JavaScript framework, is also helpful but not mandatory. Ensure that you have Laravel and Composer installed on your machine.

Step 1: Setting Up a New Laravel Project

Start by creating a new Laravel project using the Laravel installer or Composer. Open your terminal and run the following command:

composer create-project –prefer-dist laravel/laravel chat-application

This command will create a new Laravel project named “chat-application” in a directory of the same name.

Step 2: Installing the Pusher SDK

Pusher provides an easy-to-use PHP library that integrates seamlessly with Laravel. Install the Pusher SDK by running the following command in your project’s root directory:

composer require pusher/pusher-php-server

Step 3: Configuring Pusher Credentials

After installing the Pusher SDK, you need to configure your Pusher account credentials in the Laravel environment file. Open the .env file and add the following lines, replacing the placeholders with your actual Pusher credentials:

PUSHER_APP_ID=your_app_id

PUSHER_APP_KEY=your_app_key

PUSHER_APP_SECRET=your_app_secret

PUSHER_APP_CLUSTER=your_app_cluster

Step 4: Creating the Chat Interface

Now let’s create a basic chat interface using Vue.js and Laravel’s Blade templating engine. In the resources/views directory, create a new file called chat.blade.php and add the following code:

@extends('layouts.app')

@section('content')

    <div id="app">

        <chat-app></chat-app>

    </div>

@endsection

Create a new Vue component that will handle the chat functionality. In the resources/js/components directory, create a file called ChatApp.vue and add the following code:

<template>

    <div>

        <!-- Chat interface goes here -->

    </div>

</template>

<script>

export default {

    mounted() {

        // Connect to Pusher and subscribe to the chat channel

    },

}

</script>

Step 6: Establishing a Connection with Pusher

Inside the mounted method of the ChatApp.vue component, establish a connection with Pusher, and subscribe to the chat channel. Add the following code:

import Pusher from ‘pusher-js’;

export default {

    mounted() {

        // Connect to Pusher and subscribe to the chat channel

        const pusher = new Pusher(process.env.MIX_PUSHER_APP_KEY, {

            cluster: process.env.MIX_PUSHER_APP_CLUSTER,

            encrypted: true,

        });

        const channel = pusher.subscribe('chat-channel');

        // Handle received messages here

    },

}

Step 7: Sending and Receiving Messages

To handle sending and receiving messages, update the ChatApp.vue component with the following code:

import Pusher from ‘pusher-js’;

export default {

    data() {

        return {

            message: '',

            messages: [],

        };

    },

    mounted() {

        // Connect to Pusher and subscribe to the chat channel

        const pusher = new Pusher(process.env.MIX_PUSHER_APP_KEY, {

            cluster: process.env.MIX_PUSHER_APP_CLUSTER,

            encrypted: true,

        });

        const channel = pusher.subscribe('chat-channel');

        channel.bind('new-message', data => {

            this.messages.push(data);

        });

    },

    methods: {

        sendMessage() {

            // Send the message to the server

            axios.post('/message', { message: this.message })

                .then(response => {

                    // Clear the input field after sending

                    this.message = '';

                })

                .catch(error => {

                    console.error(error);

                });

        },

    },

}

Step 8: Handling Message Storage and Retrieval

Create a new route and controller to handle message storage and retrieval. In the routes/web.php file, add the following route definition:

Route::post(‘/message’, ‘App\Http\Controllers\MessageController@store’);

Next, create the MessageController using the following command in your terminal:

php artisan make:controller MessageController

Inside the store method of the MessageController, save the received message to the database:

public function store(Request $request)

{

    $message = Message::create([

        'text' => $request->message,

        // Add any other necessary fields

    ]);

    // Trigger an event to notify the connected clients about the new message

    event(new NewMessage($message));

    return response()->json($message, 201);

}

Step 9: Broadcasting the New Message Event

To broadcast the new message event to connected clients, create a new event class using the following command:

php artisan make:event NewMessage

Inside the broadcastOn method of the NewMessage event, specify the channel to broadcast to:

public function broadcastOn()

{

    return new Channel('chat-channel');

}

Step 10: Running the Application

You’re now ready to run your real-time chat application. Use the following command to start the Laravel development server:

php artisan serve

Visit http://localhost:8000/chat in your browser, and you should see the chat interface. Open another browser window or tab, log in with a different user, and start sending messages to experience real-time chat functionality.

Concluding

In this tutorial, we explored how to build a real-time chat application using Laravel and Pusher. By integrating the power of Laravel’s backend with Pusher’s real-time messaging service, you can deliver instant updates and enable seamless communication between users. This opens up a wide range of possibilities for building interactive and collaborative applications. Remember to refer to the official Laravel and Pusher documentation for more advanced features and customization options. Happy coding!

 

Discover Discover

Contacts