Recently I’ve shared a tweet about building a Slack clone app in PHP using Laravel, VueJS, TailwindCSS, and Pusher. That got some attention, so I was invited by Pusher itself to blog about using Pusher on it.

I’m not going to cover all the steps you can do to build that app here because that would be a lot of stuff to cover. Instead, I’m going to describe where and how I used the different tools that are mentioned in the post title. Maybe in the future I’ll share a series of articles that cover it and explain the basics of building this.

I got the idea of building a “Slackish” app for our annual retreat at madewithlove – the company I work for – that happened last year in Morroco (awesome place, by the way). I always struggle to decide on what to talk about, so last year I settled on a comparison of how to build the same app using PHP/Laravel and Elixir/Phoenix. For that, I defined a tiny scope: a simple chat app. You can create channels and send messages in those channels. With that, I set down and started hacking the chat app.

First I created it in PHP/Laravel, because I work with it on a daily basis so I’m really familiar with it and its ecosystems. Then in Elixir/Phoenix, I would use the running Laravel app as a comparison for building this one.

Here, however, I’m going to talk specifically about the Laravel version, since it uses Pusher. Here’s an overview of that app:

Structure diagram

Now you have an overview of the application. Let’s talk about the backend first, then we will jump into the frontend.

Backend

The application was split into two pieces. The first one is the marketing page, which is mainly a Laravel route and a regular Blade template. It outputs the HTML and there is very little logic on it. This route is only for guest users, which means that when the user is already authenticated, they will be redirected to the chat app page instead. You can find the HTML for the marketing page here.

The important aspect of it is the Login with Google button. We are leveraging Laravel’s Socialite package to handle this part. If you are not familiar with the official package, it’s an OAuth client library that you can use to build authentication systems using many Social Providers out there, like Facebook or Google. It allows us to avoid asking for passwords since the authentication flow is handled by the social providers.

When the user authenticates with the social provider, they are redirected back to our application to a specific route where we can run some logic to check if the user is a new one or an existing one. Here are the routes and the LoginController:

routes/web.php:

Route::get('/auth/{provider}', 'Auth\LoginController@create')->name('auth');
Route::get('/auth/{provider}/callback', 'Auth\LoginController@store');

app/Http/Controllers/Auth/LoginController.php:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Laravel\Socialite\AbstractUser;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest')->except(['logout', 'index']);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('auth.login');
    }

    /**
     * @param string $provider
     *
     * @return mixed
     */
    public function create($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * @param string $provider
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store($provider)
    {
        /** @var \Laravel\Socialite\AbstractUser $providerUser */
        $providerUser = Socialite::driver($provider)->user();

        $user = $this->findOrCreate($providerUser);

        auth()->login($user);

        return redirect()->home();
    }

    /**
     * @param \Laravel\Socialite\AbstractUser $providerUser
     *
     * @return mixed
     */
    private function findOrCreate(AbstractUser $providerUser)
    {
        if ($user = User::where('google_id', $providerUser->id)->first()) {
            return $user;
        }

        return User::create([
            'google_id' => $providerUser->id,
            'google_token' => encrypt($providerUser->token),
            'name' => $providerUser->name,
            'email' => $providerUser->email,
            'avatar_path' => $providerUser->getAvatar(),
        ]);
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout()
    {
        auth()->logout();

        return redirect()->route('welcome');
    }
}

Great. After we either create or find an existing user, we redirect the user to the chat app itself. But, there is another middleware protection there. Since users can create channels and send messages to these channels, we have to make sure that only specific users can see the created channel, because channels are not public. So we need to scope these channels into something else: a company.

The middleware in the chat app page will check if the current user has a company or not, and if not, it will redirect the user to the create company page where they can enter the company name (that’s the only thing we care about).

Then, while we are creating the company, this makes the perfect moment for also creating the default messaging channel: the #general channel, see the company controller for more details:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\Companies\CreateCompanyRequest;

class CompaniesController extends Controller
{
    /**
     * Protects this resource from users that already have companies.
     */
    public function __construct()
    {
        $this->middleware('has-company');
    }
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('companies.create');
    }

    /**
     * @param \App\Http\Requests\Companies\CreateCompanyRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(CreateCompanyRequest $request)
    {
        $request->user()->createCompany($request->name);

        return redirect()
            ->route('home');
    }
}

It uses a `createCompany method inside the User Eloquent model, which is basically this:

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use HasApiTokens;

    // other methods and relationhips.

    /**
     * @param string $companyName
     */
    public function createCompany(string $companyName)
    {
        $company = $this->currentCompany()->create([
            'name' => $companyName,
            'owner_id' => $this->id
        ]);

        $channel = $company->channels()->create([
            'name' => 'general',
        ]);

        $company->update([
            'default_channel_id' => $channel->id,
        ]);

        $this->currentCompany()->associate($company);
        $this->currentChannel()->associate($channel);
        $this->save();
    }
}

After that, the user is redirected to the chat app page. If you check the controller, it calls a view without passing anything to it:

<?php

namespace App\Http\Controllers;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('company');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }
}

If you open up the home.blade.php view, you will see this:

@extends('layouts.app')

@section('content')
    <div id="app"></div>
@endsection

That’s it, there’s pretty much nothing else in there. Laravel will render this view and also the stylesheets and JavaScript files that the app.blade.php layout defines:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="pusher-key" content="{{ config('broadcasting.connections.pusher.key') }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="{{ mix('css/main.css') }}" rel="stylesheet">
    <script>
        @if(auth()->check())
            window.Laravel = {!! json_encode([
                'company' => [
                    'id' => auth()->user()->currentCompany->id,
                    'name' => e(auth()->user()->currentCompany->name),
                ],
                'user' => [
                    'id' => auth()->user()->id,
                    'name' => e(auth()->user()->name),
                ],
            ]) !!}
        @endif
    </script>
</head>
<body>
    <div>
        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>

The important pieces here are:

  1. The CSRF-Token meta field, which we will hook it into axios – The HTTP library we will use; and
  2. The pusher-key meta tag, which we will use to configure Laravel Echo. This key is public, so don’t worry about it being leaked, there is an authentication process which we will cover as well.

So, now let’s jump in the frontend aspects.

Frontend

If you notice the tweet date and repository, there is a few months difference between them. That’s because I built the functioning application a few months ago, but it didn’t look like Slack at all. It was using Bootstrap, although it was already working. Then I saw a Slack Clone that Adam Wathan wrote using TailwindCSS, so I thought: hey, I already have a chat application working, maybe I can use that skin. So I did.

The chat application has two main VueJS components, one for the logic and dealing with Vuex methods (which I call a container component) and another one with the visual aspects of it, so all the HTML and DOM events and so on. The visualization component receives all data from the container component via props and also enables some events that the container component can add listeners to.

I did this mainly because I wanted to reuse the same visualization component between the Laravel application and the Phoenix one, and it worked quite well. I only had to write the container components for each of these applications. Let’s see how the Laravel version of it was built:

<template>
    <chat-app
        :messages="messages"
        :channels="channels"
        :current-channel="currentChannel"
        :current-user="user"
        :current-company="company"
        @new-message="newMessage"
        @new-channel="newChannel"
        @join-channel="joinChannel"
        @logout="logout"
    />
</template>

<script>
    import {mapState, mapActions} from 'vuex';

    import {
        SEND_NEW_MESSAGE, 
        CREATE_NEW_CHANNEL, 
        LIST_CHANNELS, 
        LOGOUT
    } from './store/actions';
    import ChatApp from './components/ChatApp.vue';
    import { NEW_CHANNEL, NEW_MESSAGE, JOINED_CHANNEL } from './store/mutations';


    export default {
        components: {
            ChatApp
        },
        computed: mapState([
            'messages', 
            'channels', 
            'currentChannel', 
            'user', 
            'company',
        ]),
        methods: {
            ...mapActions({
                newMessage: SEND_NEW_MESSAGE,
                newChannel: CREATE_NEW_CHANNEL,
            }),
            joinChannel(channel) {
                if (this.currentChannel && this.currentChannel.id === channel.id) {
                    return;
                }

                if (this.currentChannel) {
                    Echo.leave(`channels.${this.currentChannel.id}`);
                }

                try {
                    Echo.private(`channels.${channel.id}`)
                        .listen('NewMessage', (e) => {
                            this.$store.commit({
                                type: NEW_MESSAGE,
                                message: e,
                            });
                        });

                    this.$store.commit({
                        type: JOINED_CHANNEL,
                        channel
                    });
                } catch (e) {
                    console.log(e);
                }
            },
            logout() {
                this.$store.dispatch(LOGOUT);
            }
        },
        mounted() {
            this.$store.dispatch(LIST_CHANNELS);

            Echo.private(`companies.${window.Laravel.company.id}`)
                .listen('ChannelCreated', (e) => {
                    this.$store.commit({
                        type: NEW_CHANNEL,
                        channel: e.channel
                    });
                });
        }
    }
</script>

Let’s dissect the main pieces here:

  1. Whenever this component is mounted, we dispatch a Vuex action to list the channels, and we also start listening to a private event that is company scoped. This event is triggered by the backend and whenever it happens, clients are notified about it and this callback function is executed, which triggers a new Vuex mutation that adds the new channel to the list (don’t worry, we will see how events are fired to Pusher later on);
  2. Also, whenever the user triggers the “join channel” event on the visualization component (which is when the user clicks on a particular channel), we are going to listen to another private channel. Don’t get confused with our Channel domain model, the Broadcasting component also has channels, where we listen events on. In this broadcasting channel, we are going to receive messages sent to our domain channels and this callback is going to be executed, committing another Vuex mutation that adds the message to the message list;

Now, you might be wondering how Pusher is configured and used. Let’s discuss this.

Closing the circle

Let’s go back to the backend. First, we have to pull the Pusher SDK via composer. Then, we need to configure the Broadcasting component in Laravel to actually use the Pusher driver. We can do so by using environment variables. Laravel ships with a dotenv approach, so there is a .env.example file which you can copy to .env and this will be loaded into PHP env. We have to define some keys for the Pusher SDK to work:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=SECRET_APP_ID
PUSHER_APP_KEY=APP_PUBLIC_KEY
PUSHER_APP_SECRET=APP_SECRET_KEY

You can get your credentials at the Pusher console after you create your account (it’s free to get started. Thanks, Pusher :D). That covers the backend configuration. Now, Laravel Broadcasting component can send events to Pusher which our frontend can listen to. Let’s see the frontend configuration.

Remember the app.blade.php has a pusher-key meta tag? This is used by the resources/assets/js/bootstrap.js file to configure Laravel Echo, see:

// ...
import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: document.head.querySelector('meta[name="pusher-key"]').content,
});

You will need the laravel-echo, as well as the pusher-js NPM packages, as you can see here. With that, we are done with the configuration of both the backend and the frontend.

Protecting broadcasting channels

If you look closely at the logic for listening on broadcasting channels in the Laravel Echo usage, we are using the Echo.private() method. This doesn’t magically turn things into private ones. Internally, Echo will send an HTTP request to our backend and ask if the current user (authenticated in the session) has access to the given channel. We can define how this authorization happens per channel in the routes/channels.php. For instance, the first channel we listen to is the company one:

mounted() {
    this.$store.dispatch(LIST_CHANNELS);

    Echo.private(`companies.${window.Laravel.company.id}`)
        .listen('ChannelCreated', (e) => {
            this.$store.commit({
                type: NEW_CHANNEL,
                channel: e.channel
            });
        });
}

This one has a pattern of companies.ID and if you check this same channel in the channels route file, you will find the callback that handles the authorization:

<?php

use App\{User, Company};

Broadcast::channel('companies.{company}', function (User $user, Company $company) {
    if (!$user->currentCompany || !$user->currentCompany->is($company)) {
        return false;
    }

    return [
        'id' => $user->id,
        'name' => $user->name,
        'avatar_path' => $user->avatar_path,
    ];
});

This authorization callback can also be extracted to a class, but a callback function is fine for now. In this authorization callback, you can return :

  • false if the user is not authorized to listen to this channel;
  • true if the user is authorized; or
  • an array of data, which means “true” and the data is going to be used to identify the current user (socket) in a presence channel, which we are not going to cover here.

So by doing that, our frontend will be authorized to listen to the company channel if the user has access to the company they are trying to listen to. Really neat.

When a user creates a company, our Vuex action will send an HTTP request to our backend, see the Chat service in the resources/assets/js/api folder:

export function createChannel(channelName) {
    return axios.post(`/api/channels`, {
        name: channelName,
    });
}

If you check the routes/api.php file, where we define the API routes, you can see this:

<?php

use Illuminate\Http\Request;
use Illuminate\Routing\Router;

Route::middleware('auth:api')->group(function (Router $router) {
    // ...
    $router->resource('channels', 'ChannelsController', [
        'only' => ['store', 'index'],
    ]);
});

When you open the ChannelsController, you can see the interesting part:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\ChannelCreated;
use App\Http\Resources\ChannelCollection;
use App\Http\Requests\Channels\CreateChannelRequest;

class ChannelsController extends Controller
{
    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function index(Request $request)
    {
        return ChannelCollection::make($request->user()->currentCompany->channels);
    }

    /**
     * @param \App\Http\Requests\Channels\CreateChannelRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(CreateChannelRequest $request)
    {
        $channel = $request->user()->currentCompany->createChannel($request->name);

        broadcast(new ChannelCreated($channel));

        return response()->json('', 201);
    }
}

In the store() method, we are creating the Channel inside the current company of the user, after that, we are broadcasting an event. This is where we are sending a message to Pusher, and if you check this Event name, it matches with the event we are listening to on the frontend:

Echo.private(`companies.${window.Laravel.company.id}`)
    .listen('ChannelCreated', (e) => {
        this.$store.commit({
            type: NEW_CHANNEL,
            channel: e.channel
        });
    });

The event class is simple:

<?php

namespace App\Events;

use App\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ChannelCreated implements ShouldBroadcast
{
    use SerializesModels;

    /**
     * @var \App\Channel
     */
    public $channel;

    /**
     * Create a new event instance.
     *
     * @param \App\Channel $channel
     */
    public function __construct(Channel $channel)
    {
        $this->channel = $channel;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel("companies.{$this->channel->company_id}");
    }
}

This is a Laravel event. And here we are implementing a ShouldBroadcast interface, which tells Laravel that this event is going to be sent to our broadcasting driver, which means that this event is also going to be fired in the frontend.

Every public property in this event, will also make it to the frontend, in the object sent to the listener callback. So this means our channel object will get to the JS, which will be added to the channels list and be displayed in the UI.

The broadcastOn() method in the event tells Laravel what is the broadcasting channel that we are sending this event to.

Wrapping up

So I think that’s it. This article was meant to be an overview of how I built Slackish and how you can use Pusher in your Laravel application for realtime goodies.

You can view the full code for the app on github.

I hope this was useful to you, see you next time!

Latest Posts By Luiz Antonio