Getting started: Pub/Sub in Laravel

This guide will get you started with Ably Pub/Sub in Laravel 12 or 13.

You'll learn how to create a client and establish a connection to Ably using the Ably Laravel Broadcaster service provider and Ably Laravel Echo (a Laravel Echo fork with native Ably integration). You'll also cover creating an event to broadcast messages from the backend, and setting up a frontend client that receives messages from a channel and sends new ones through your Laravel API.

Screenshot of the completed Laravel Pub/Sub application showing a web interface with a message input field and realtime message display. The interface demonstrates the key features you'll build including publishing messages and subscribing to receive messages in realtime.

For a complete chat app built with the Ably Laravel Broadcaster and Ably Laravel Echo, see the Ably Laravel Broadcast app on GitHub. It has public rooms for guests, user login, private rooms with presence for logged-in users, and typing indicators in private rooms. It is a separate app, so its setup and code differ from this guide.

Prerequisites

  1. Sign up for an Ably account.

  2. Create a new app, and create your first API key in the API Keys tab of the dashboard.

  3. Your API key needs the publish, subscribe, presence, history and channel-metadata capabilities. The root key created with a new app has all of them.

  4. Install PHP and Composer. Laravel 12 needs PHP version 8.2 or greater, and Laravel 13 needs PHP version 8.3 or greater.

  5. Install Node.js version 22.12 or greater.

  6. Create a new Laravel project and install the Ably Laravel Broadcaster. When php artisan install:api asks whether to run the pending database migrations, answer yes:

    # Create a new Laravel project
    composer create-project laravel/laravel ably-laravel-quickstart
    cd ably-laravel-quickstart
    
    # Install the Ably Laravel Broadcaster
    composer require ably/laravel-broadcaster
    
    # Create routes/api.php for the API route in Step 3
    php artisan install:api
  7. Start the PHP development server in one terminal window:

    php artisan serve # http://localhost:8000

    Then install the frontend dependencies and start the Vite development server in a second terminal window:

    npm install
    npm run dev

(Optional) Install Ably CLI

Use the Ably CLI as an additional client to quickly test Pub/Sub features. It can simulate other clients by publishing messages, subscribing to channels, and managing presence states.

ably init installs the Ably CLI, authenticates, and sets the default app and API key in a single command:

npx @ably/cli init

Step 1: Configure the Ably Laravel Broadcaster

The Ably Laravel Broadcaster connects Laravel's broadcasting system to Ably. In this step you set your Ably API key, publish the broadcasting configuration, and register the route that Echo uses to get tokens.

First, open the .env file in the root of your project. A new Laravel project already has a BROADCAST_CONNECTION=log line, so change its value to ably. Then add your Ably API key and the MAU setting:

Laravel

1

2

3

BROADCAST_CONNECTION=ably
ABLY_KEY=demokey:*****
ABLY_MAU_ACCOUNT=true
API key:
DEMO ONLY

Publish Laravel's broadcasting configuration file. This creates config/broadcasting.php, which already includes an ably connection:

php artisan config:publish broadcasting

This guide doesn't use php artisan install:broadcasting --ably, because that command sets up a frontend that connects through Ably's Pusher protocol adapter with pusher-js, instead of Ably Echo.

Open config/broadcasting.php and add the mau_account and guest_id_prefix lines to the ably connection in the connections array. mau_account turns on guest client IDs, and is required on MAU accounts. guest_id_prefix is optional and sets the start of each guest client ID, which defaults to guest:. The broadcaster reads these settings only from this file, so ABLY_MAU_ACCOUNT in .env has no effect until you add them:

Laravel
1'ably' => [2    'driver' => 'ably',3    'key' => env('ABLY_KEY'),4    'mau_account' => env('ABLY_MAU_ACCOUNT', false),5    'guest_id_prefix' => env('ABLY_GUEST_ID_PREFIX', 'guest:'),6],

Create a routes/channels.php file for your channel authorization rules. This guide only uses a public channel, which needs no rule, but Laravel registers its broadcasting routes only when this file exists:

Laravel

1

2

3

4

5

6

7

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Open bootstrap/app.php and add a channels line to the withRouting() call. This loads routes/channels.php and registers the /broadcasting/auth route, which Echo calls to get a token for each visitor. The api line is already there, because php artisan install:api added it in the prerequisites:

Laravel
1->withRouting(2    web: __DIR__.'/../routes/web.php',3    api: __DIR__.'/../routes/api.php',4    commands: __DIR__.'/../routes/console.php',5    channels: __DIR__.'/../routes/channels.php',6    health: '/up',7)

Step 2: Create the event that will be broadcast

To send events from Laravel to Ably, create an event file by running the following command in your terminal:

php artisan make:event PublicMessageEvent

This command will create a PublicMessageEvent.php file in the app/Events directory. Replace the contents of the file with the following to handle the broadcasting of messages to a public channel:

Laravel

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * Event for broadcasting public messages.
 */
class PublicMessageEvent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $channelName;
    public $message;

    /**
     * Create a new event instance.
     */
    public function __construct($channelName, $message)
    {
        $this->channelName = $channelName;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<\Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [new Channel($this->channelName)];
    }
}

Step 3: Add an API route to broadcast

To handle API requests from the frontend, replace the contents of routes/api.php, which php artisan install:api created, with the following route:

Laravel

1

2

3

4

5

6

7

8

9

10

11

12

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Events\PublicMessageEvent;

Route::post('/public-event', function (Request $request) {
    $channelName = $request->input('channelName');
    $message = $request->input('message');
    broadcast(new PublicMessageEvent($channelName, $message));
    return response()->json(['success' => true, 'message' => 'Event broadcasted']);
})->middleware('throttle:60,1'); // 60 requests/minute are allowed.

The /api/public-event endpoint accepts POST requests with channelName and message parameters, and broadcasts the event to the specified channel.

Step 4: Test the API route

To test the API route, first you need at least one client subscribed to the channel. Use the Ably CLI to subscribe, with the same Ably app as the API key in your .env file. The broadcaster adds a public: prefix to the names of public channels, so my-first-channel in Laravel is public:my-first-channel in Ably:

ably channels subscribe public:my-first-channel

Now publish a message to the channel using the API route you created in Step 3. Use curl or any HTTP client to send a POST request. The route responds with {"success":true,"message":"Event broadcasted"}, and the message appears in the terminal where the Ably CLI is subscribed:

curl --location --request POST 'localhost:8000/api/public-event' \
--header 'Content-Type: application/json' \
--data-raw '{
    "channelName":"my-first-channel",
    "message":"A message sent from my first client!"
}'

Step 5: Frontend setup

Install Ably's fork of Laravel Echo and axios in your Laravel project. Echo installs Ably's Pub/Sub JavaScript SDK for you, so you don't install the ably package yourself:

npm install @ably/laravel-echo@^1.1 axios

Replace the contents of resources/js/app.js with the following Echo configuration. The page you create in Step 6 loads this file. Echo requests a token from your app's /broadcasting/auth route, so your Ably API key stays on the server:

Laravel

1

2

3

4

5

6

7

8

9

10

11

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// Configure Laravel Echo with Ably
import Echo from '@ably/laravel-echo';

window.Echo = new Echo({
    broadcaster: 'ably',
});

Step 6: Create a frontend file to listen for events

Create a new Blade view file named echo.blade.php in the resources/views directory. It is the page rendered in your browser as your frontend client, and it loads Laravel's default resources/css/app.css for its Tailwind styles and resources/js/app.js for Echo:

Laravel

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Echo with Ably</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans max-w-4xl mx-auto p-5 bg-gray-50 leading-relaxed">
    <h1 class="text-slate-800 text-4xl mb-8 text-center font-bold tracking-tight">Laravel Echo with Ably Test</h1>

    <form id="messageForm" class="my-5 p-5 bg-white rounded-lg shadow-sm">
        <h3 class="text-slate-700 text-xl mb-4 font-semibold">Send a Message</h3>
        <input type="text" id="channelName" placeholder="Channel name" value="my-first-channel"
               class="w-48 px-4 py-3 m-1 border-2 border-gray-200 rounded-md text-sm bg-white transition-colors focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100">
        <input type="text" id="messageInput" placeholder="Enter your message" required
               class="w-48 px-4 py-3 m-1 border-2 border-gray-200 rounded-md text-sm bg-white transition-colors focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100">
        <button type="submit" class="px-6 py-3 m-1 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700 active:translate-y-px">Send Message</button>
    </form>

    <div id="messages" class="border-2 border-gray-200 rounded-lg p-4 h-80 overflow-y-auto my-5 bg-white shadow-sm">
        <p class="message py-2 border-b border-gray-100 text-gray-600"><strong>Listening for messages...</strong></p>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Echo instance:', window.Echo);

            console.log('Attempting to join channel: my-first-channel');

            const channel = Echo.channel('my-first-channel')
                .subscribed(() => {
                    console.log('Successfully subscribed to channel');
                })
                .listenToAll((eventName, data) => {
                    console.log("Event :: " + eventName + ", data is :: " + JSON.stringify(data));
                })
                .listen('PublicMessageEvent', (data) => {
                    document.getElementById('messages').innerHTML +=
                        `<div class="message py-2 border-b border-gray-100 text-gray-600"><strong>Received:</strong> ${data.message}</div>`;
                })
                .error((err) => {
                    if (err?.statusCode === 401){
                        alert("You don't have the access to join this public room.");
                    } else {
                        alert("An error occurred while trying to join a public room, check the console for details.");
                    }
                    console.error(err);
                });

            // Handle form submission
            document.getElementById('messageForm').addEventListener('submit', function(e) {
                e.preventDefault();

                const channelName = document.getElementById('channelName').value;
                const message = document.getElementById('messageInput').value;
                const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

                if (!message.trim()) {
                    alert('Please enter a message');
                    return;
                }

                // Send message to Laravel API
                fetch('/api/public-event', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        channelName: channelName,
                        message: message
                    })
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Message sent successfully:', data);
                    document.getElementById('messageInput').value = ''; // Clear the input
                    document.getElementById('messages').innerHTML +=
                        `<div class="message py-2 border-b border-gray-100 text-gray-600"><strong>Sent:</strong> ${message} (to ${channelName})</div>`;
                })
                .catch(error => {
                    console.error('Error sending message:', error);
                    alert('Error sending message. Check console for details.');
                });
            });
        });
    </script>
</body>
</html>

Add the route to serve the frontend file in routes/web.php to expose this new file to the browser:

Laravel

1

2

3

4

5

6

7

8

9

10

11

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/echo', function () {
    return view('echo');
});

In your browser, open http://localhost:8000/echo to see the frontend page. Open the browser console: Successfully subscribed to channel means that Echo connected as a guest. If you see error 40161 instead, check the mau_account line in config/broadcasting.php from Step 1.

Type a message in the form and select Send Message, or send a POST request with curl. The message appears in the list below the form:

curl --location --request POST 'localhost:8000/api/public-event' \
--header 'Content-Type: application/json' \
--data-raw '{
    "channelName":"my-first-channel",
    "message":"A message sent from my first client!"
}'
Screenshot showing the Laravel Echo with Ably test page running in a browser

Next steps

Continue to explore the documentation with PHP as the selected framework:

You can also explore the Ably CLI further, or visit the Pub/Sub API references.