This is a guest blog post written by Remo Blaser.

I’m Remo, a passionate Web-developer working for a small agency called WeLoveYou in Switzerland.

Using Laravel and new technologies is my daily business and I love to talk about all these stuff either on my blog, on Twitter or any other site which lets me talk about something.

Laravel is one of the most used and loved PHP frameworks currently out there and it comes many useful features.

One of them is an integration to Pusher and in this blog post we’ll use Pusher to send events in realtime to a frontend, using Laravel 5.

Setting up a Laravel Project

Setting up a Laravel Project is very easy.

First of all, we will create a fresh installation of Laravel by using Composer:

composer create-project laravel/laravel HelloPusher && cd HelloPusher

Whilst Laravel comes with Pusher support built in, we still need to configure it.

So let’s head into our configuration and open up config/broadcasting.php.

Inside the connection array you will see a pusher driver, ready to be filled with our Pusher credentials

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_KEY'),
    'secret' => env('PUSHER_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [],
]

So let’s edit our .env file on the root level of our Project and add this part, replace the x’s with your credentials from your Pusher dashboard:

PUSHER_KEY=xxxxxxxxxxxxxxxxxxxx
PUSHER_SECRET=xxxxxxxxxxxxxxxxxxxx
PUSHER_APP_ID=xxxxxx

Note: If you’re using the EU or AP Cluster, make sure to update the options array in your broadcasting.php config since Laravel defaults to using the US Server. You can use all the options the Pusher PHP Library supports.

Connecting Laravel and Pusher

For Laravel to work with Pusher, we need to get the pusher/pusher-php-server composer-package. So let’s install this first:

composer require pusher/pusher-php-server

Now we can create an event which we will fire every time we would like to send a notification through Pusher. We can use the artisan tool to create an event for us:

php artisan make:event HelloPusherEvent

This creates a Event in /app/Events/HelloPusherEvent.php which we now change to fit our needs:

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
/**
 * Just implement the ShouldBroadcast interface and Laravel will automatically 
 * send it to Pusher once we fire it 
**/
class HelloPusherEvent extends Event implements ShouldBroadcast 
{
    use SerializesModels;

    /**
     * Only (!) Public members will be serialized to JSON and sent to Pusher
    **/
    public $message;

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

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return ['my-channel'];
    }
}

Note: Only public members will be Serialized (thanks to the SerializesModels Trait) and sent to Pusher. Protected and private members will be ignored.

Finally, let’s create some Laravel routes to connect our application.

In routes.php create the following routes:

<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

Route::get('/pusher', function() {
    event(new App\Events\HelloPusherEvent('Hi there Pusher!'));
    return "Event has been sent!";
});

Time to test everything! Visit your Pusher dashboard and load up the debug console for the Pusher application that you’re using for this blog post.

Now start up the built in PHP Server with

php artisan serve

And visit http://localhost:8000/pusher. After a small wait while the application loads, you should be able to see your message in your dashboard:

View your event from your Pusher.com Dashboard

Consume Events in JS

Now to the fun part. We will now wait for these events in our Frontend, for this, i’ve created a simple HTML in /resources/views/home.blade.php which looks like this

<!DOCTYPE html>
<html>
  <head>
    <title>Talking with Pusher</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <div class="content">
        <h1>Laravel 5 and Pusher is fun!</h1>
        <ul id="messages" class="list-group">
        </ul>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://js.pusher.com/3.1/pusher.min.js"></script>
    <script>
      //instantiate a Pusher object with our Credential's key
      var pusher = new Pusher('YOUR-KEY', {
          cluster: 'eu',
          encrypted: true
      });

      //Subscribe to the channel we specified in our Laravel Event
      var channel = pusher.subscribe('my-channel');

      //Bind a function to a Event (the full Laravel class)
      channel.bind('App\\Events\\HelloPusherEvent', addMessage);

      function addMessage(data) {
        var listItem = $("<li class='list-group-item'></li>");
        listItem.html(data.message);
        $('#messages').prepend(listItem);
      }
    </script>
  </body>
</html>

Now when you load http://localhost:8000 now we should see the title “Laravel 5 and Pusher is fun!”.
Open up another Tab and make a request to the Pusher URL (http://localhost:8000/pusher). Switch back to the first tab and you should see our message added to our list.

We've received our message in our frontend

That’s it! In a few minutes we were able to set up Pusher and Laravel and now we’re ready to create our realtime app.

Links