Building a Real-Time Chat Application with Laravel and Pusher: A Step-by-Step Guide

20 Oct 2024 01:10 AM

In today’s digital world, real-time communication is crucial for engaging user experiences. Building a chat application can be an exciting project, and in this guide, we’ll walk through creating a real-time chat app using Laravel and Pusher. Let's dive in!

Prerequisites

Before we start, ensure you have the following:

  • Basic knowledge of PHP and Laravel
  • Composer installed
  • Node.js and npm installed
  • A Pusher account (you can sign up for free)

Step 1: Set Up Laravel

First, let’s create a new Laravel project. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel laravel-chat
cd laravel-chat

Step 2: Configure Environment Variables

After creating your Laravel application, navigate to the root of your project and set up your environment variables. Open the .env file and set the following:

APP_NAME=Laravel Chat
APP_ENV=local
APP_KEY=base64:YourAppKey
APP_DEBUG=true
APP_URL=http://localhost

# Database configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=chat_app
DB_USERNAME=root
DB_PASSWORD=

# Pusher configuration
PUSHER_APP_ID=your_pusher_app_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_APP_CLUSTER=your_pusher_app_cluster

Make sure to replace the placeholder values with your actual Pusher credentials.

Step 3: Set Up Database

Create a new database for your application. If you're using MySQL, you can create a database named chat_app. Then, run the following command to create a migration for messages:

php artisan make:migration create_messages_table --create=messages

Open the newly created migration file in database/migrations/ and define the schema:

public function up()
{
    Schema::create('messages', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->text('message');
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

Step 4: Create the Message Model

Now, let’s create a model for our messages:

php artisan make:model Message

Open the Message.php model file and define the fillable properties:

class Message extends Model
{
    protected $fillable = ['username', 'message'];
}

Step 5: Create the Chat Controller

Next, create a controller to handle our chat logic:

php artisan make:controller ChatController

In ChatController.php, add the following methods:

use App\Models\Message;
use Illuminate\Http\Request;
use Pusher\Pusher;

class ChatController extends Controller
{
    public function index()
    {
        return view('chat.index');
    }

    public function sendMessage(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'message' => 'required',
        ]);

        $message = Message::create($request->all());

        // Initialize Pusher
        $pusher = new Pusher(
            env('PUSHER_APP_KEY'),
            env('PUSHER_APP_SECRET'),
            env('PUSHER_APP_ID'),
            ['cluster' => env('PUSHER_APP_CLUSTER')]
        );

        // Trigger an event
        $pusher->trigger('chat', 'message', $message);

        return response()->json(['status' => 'Message Sent!']);
    }
}

Step 6: Set Up Routes

Open routes/web.php and add the following routes:

use App\Http\Controllers\ChatController;

Route::get('/chat', [ChatController::class, 'index']);
Route::post('/chat/send', [ChatController::class, 'sendMessage']);

Step 7: Create the Chat View

Create a new Blade view file at resources/views/chat/index.blade.php and add the following HTML and JavaScript code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Chat</title>
    <script src="https://js.pusher.com/7.0/pusher.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Laravel Chat</h1>
    <div id="messages"></div>
    <input type="text" id="username" placeholder="Username">
    <input type="text" id="message" placeholder="Message">
    <button id="send">Send</button>

    <script>
        // Enable pusher logging - don't include this in production
        Pusher.logToConsole = true;

        var pusher = new Pusher('your_pusher_app_key', {
            cluster: 'your_pusher_app_cluster'
        });

        var channel = pusher.subscribe('chat');
        channel.bind('message', function(data) {
            $('#messages').append('<p><strong>' + data.username + ':</strong> ' + data.message + '</p>');
        });

        $('#send').click(function() {
            var username = $('#username').val();
            var message = $('#message').val();
            $.post('/chat/send', { username: username, message: message });
            $('#message').val('');
        });
    </script>
</body>
</html>

Replace your_pusher_app_key and your_pusher_app_cluster with your actual Pusher values.

Step 8: Start the Server

Now, you’re ready to test your chat application. Start your Laravel server:

php artisan serve

Visit http://localhost:8000/chat in your browser. Open multiple tabs or browsers to test sending and receiving messages in real-time!

Conclusion

Congratulations! You’ve built a real-time chat application using Laravel and Pusher. This project is a great starting point for exploring more complex features like user authentication, message storage, and more.

Feel free to expand upon this foundation and make it your own. Happy coding!

 

1
12