This blog post was written under the Pusher Guest Writer program.

A photo feed is a web feed that features image enclosures. It provides an easy, standard way to reference a list of images. Instagram and Flickr are examples of such a feed.

Today, we will create a Realtime Photo Feed using Laravel and Pusher. With the release of Echo, Laravel has provided an out of the box solution for implementing realtime features using event broadcasting without the need of polling applications. It is simple to get started in a few minutes.

A basic understanding of Laravel and Vue is needed to understand this tutorial.

Setup an App on Pusher

First, you need to sign up on Pusher and create a new app.

Install Laravel, Pusher SDK and Echo

Then, we will grab a fresh copy of Laravel:

laravel new realtime-photo-feed-laravel-pusher

This will install the latest version of the Laravel framework and download the necessary dependencies. Next, we will install the Pusher PHP SDK using Composer:

composer require pusher/pusher-php-server

After this, we will install the JavaScript dependencies:

npm install

Now, we need to install two Javascript libraries necessary for realtime event broadcasting: Laravel Echo and Pusher JS

npm install --save laravel-echo pusher-js

We require some form of user authentication mechanism to demonstrate the functionality. Let us use the default authentication scaffolding provided by Laravel:

php artisan make:auth

Configuration

First, we need to set the APP_ID, APP_KEY, APP_SECRET and APP_CLUSTER in the environment file. We can get these details in our Pusher app dashboard:

# .env

APP_URL=your-application-url

BROADCAST_DRIVER=pusher

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

Next, we need to create a fresh Echo instance in our applications’s JavaScript. We can do so at the bottom of our resources/assets/js/bootstrap.js file:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-app-key',
    cluster: 'ap2',
    encrypted: true
});

Our Application

We will create a realtime photo feed similar to what Instagram does. The core feature is to display the new photos in realtime, without the need of polling the application continuously or refreshing the page. We will not cover anything relating to writing CRUD functionality using Laravel. We will concentrate on the code necessary for implementing the realtime photo feed feature. The code is available on a Github repository for cloning and understanding purposes.

Migrations

Next, we need a photos table, where we can record all the photos uploaded by a user. Let us create a model and migration:

php artisan make:model Photo -m

The photos table would require the following fields:

  1. URL of each uploaded photo
  2. A field to link the photo to the user who uploaded it

Below is our migration file for the photos table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePhotosTable extends Migration
{

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('photo_url');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('photos');
    }
}

Uploading Photos

We need to handle the request for uploading photos, move the uploaded photo to a specified directory and store the photo_url in database table. First, we will create a UploadPhotoController which will handle this request:

php artisan make:controller UploadPhotoController

When using the public disk, the files are stored in the storage/app/public directory. To make them accessible for the web users, we need to create a symbolic link with the following command:

php artisan storage:link
  • Please make a note that, the GD extension needs to be installed on the the server to successfully upload the file

We will store the photos on the public disk, which is a convention for where to place assets we want to be publicly accessible. Then, we can grab the URL for the image to store for this photo in the database row.

# routes/api.php

Route::middleware('auth:api')->post('/upload/photo', 'UploadPhotoController');


# UploadPhotoController.php

public function __invoke()
{
    $file = request('photo');
    $path = $file->hashName('profiles');

    $disk = Storage::disk('public');

    $disk->put(
        $path, $this->formatImage($file)
    );

    $photo = request()->user()->photos()->create([
        'photo_url' => $disk->url($path),
    ]);

    return $photo->load('user');
}

Broadcasting Feed

Whenever a new photo is uploaded, we need to fire an event which will be broadcasted over Pusher to a private channel. Let us first create the NewPhoto event:

php artisan make:event NewPhoto

broadcastOn method

The event should implement a broadcastOn method. This method must return the channels to which the event should be broadcasted on.

broadcastWith method

By default, Laravel will broadcast all the public properties in JSON format as the event payload. We can define our logic to broadcast only the necessary data in the broadcastWith method.

Below is our NewPhoto event:

namespace App\Events;

use App\Photo;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewPhoto implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $photo;

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return PrivateChannel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('photos');
    }
}

Now, we need to start our queue to actually listen for jobs and broadcast any events that are recorded. We can use the database queue listener on our local environment:

php artisan queue:listen

Next, we need to broadcast this event to other users on the same channel. Let us use the broadcast helper provided by Laravel to fire the event whenever a new photo is uploaded:

# UploadPhotoController.php

public function __invoke()
{
    $file = request('photo');
    $path = $file->hashName('profiles');

    $disk = Storage::disk('public');

    $disk->put(
        $path, $this->formatImage($file)
    );

    $photo = request()->user()->photos()->create([
        'photo_url' => $disk->url($path),
    ]);

    broadcast(new NewPhoto($photo))->toOthers();

    return $photo->load('user');
}

Listening to the Feed

Installation and configuration of Laravel Echo is a must before we can start listening to photo feeds. We have covered the installation process in detail in the section above. Please go through it if you might have skipped it.

We can listen to a private channel using Echo.private(channel). As we have broadcasted the NewPhoto event on a private channel, we will use Echo.private():

listen() {
    Echo.private('photos')
        .listen('NewPhoto', (e) => this.photos.unshift(e.photo));
}

Authorization

As we are listening on a private channel, we need to authenticate that the current logged in user should be able to listen on this private channel. Laravel Echo will automatically call the necessary authorization routes if we are listening to a private channel. But, we need to write the authentication logic which will actually authorize the user.

Authorization logic is written in the routes/channels.php. For the sake of example, we will simply return true without performing any authorization logic:

Broadcast::channel('photos', function ($user) {
    return true;
});

Now, whenever a new photo is uploaded, the event would broadcast over Pusher. Next, we listen to photos channel and push the new photo to our photos array in our Vue component.

Below is the JavaScript part of our Example component written using Vue.js

# HTML

<span>Select New Photo</span>
<input ref="photo" type="file" class="form-control" name="photo" @change="update">

# JavaScript
<script>
    export default {
        props: ['user'],
        data() {
            return {
                photos: []
            }
        },
        mounted() {
            this.getPhotos();
            this.listen();
        },
        methods: {
            update(e) {
                e.preventDefault();

                axios.post('/api/upload/photo?api_token=' + this.user.api_token, this.gatherFormData())
                    .then(response => this.photos.unshift(response.data));
            },
            /**
             * Gather the form data for the photo upload.
             */
            gatherFormData() {
                const data = new FormData();

                data.append('photo', this.$refs.photo.files[0]);

                return data;
            },
            getPhotos() {
                axios.get('/api/photos').then(response => this.photos = response.data);
            },
            listen() {
                Echo.private('photos')
                    .listen('NewPhoto', (e) => this.photos.unshift(e.photo));
            }
        },
    }
</script>

And here the demonstration of our functionality:

Conclusion

In this article, we have shown you How to Build a Realtime Photo Feed. We have covered the configuration options you need to get started. The example above should help you fill in the gaps and give an overview of some of the other configuration options available to you.

The code is hosted on a public Github repository. You can download it for educational purposes. How do you use Laravel and Pusher for photo feeds? Can you think of any advanced use cases for this library? Let us know in the comments!