Video Slideshows with Cloudinary & Laravel

Banner for a MediaJam post

Eugene Musebe

Cloudinary is a Software-as-a-Service (SaaS) solution for managing all your web or mobile application’s media assets in the cloud. Cloudinary offers an end-to-end solution for all your image and video needs, including upload, storage, administration, transformation, and optimized delivery. Laravel is a PHP framework developed with developer productivity in mind. The framework also aims to evolve with the web and has already incorporated several new features and ideas in the web development world—such as job queues, API authentication out of the box, real-time communication, and much more.

Introduction

Slideshows are the perfect addition to your media collection. They make your social media content engaging, fun, and memorable and are great for business promotional purposes. In this article, we will create a video slideshow using Laravel and Cloudinary.

Some use cases for slideshows include:

  • Creating a personalized video of a user’s recent items.

  • Creating a personalized video of items a user left in their shopping cart.

  • Creating a daily sale video of different products automatically.

  • Creating a real-estate video out of apartment images.

The possibilities are endless since with dynamic transformations like Content-Aware Crop you can create video slideshows for your Instagram, WhatsApp, and TikTok Stories.

Let's get started.

PHPSandbox and Github

The final project can be viewed on PHPSandbox and the entire source code is available on my Github repository.

Prerequisites

Using Cloudinary in your Laravel projects is pretty straightforward. However, for you to be able to easily follow along,

you need to have a good command of your terminal, Git, and entry knowledge of PHP specifically with the Laravel

framework.

Getting Started

Being that Laravel is a PHP Framework, we will need Composer. Like any modern PHP framework, Laravel uses Composer to manage its dependencies. So, before we can

start to ensure you have Composer installed on your machine. Follow step 1 below to install Composer and PHP.

  1. Install Composer and PHP on

your development or production machine.

  1. Install Laravel

  2. Via Composer:

composer create-project --prefer-dist laravel/laravel cloudinary-video-slideshow

  1. Via Laravel Installer

`composer global require laravel/installer

laravel new cloudinary-video-slideshow

  1. In step 2 above we have installed the Laravel Installer and used it to scaffold a new application in the folder cloudinary-video-slideshow. With Laravel installed, we should be able to start and test the server ensuring everything is okay. Change the directory to the project folder and run the local development server by typing the following commands:

cd cloudinary-video-slideshow

php artisan serve

The Laravel project is now up and running. When you open http://localhost:8000 on your computer, you should see the image below:

Laravel Server Running

Setting up Cloudinary’s Laravel SDK

Cloudinary has a tonne of features from media upload, storage, administration, and manipulation to optimization and delivery. In this article, we will use Cloudinary Video Transformations to combine existing or newly uploaded media files to create a slideshow.

  1. Sign up for a free Cloudinary account then navigate to the Console page and take note of your Cloud name, API Key and

API Secret.

Cloudinary Dashboard

  1. Install Cloudinary’s Laravel SDK:

composer require cloudinary-labs/cloudinary-laravel

Note: Please ensure you follow all the steps in the #Installation section. Publish the configuration file and add

the Cloudinary credentials you noted in Step 1 to the .env file.

1CLOUDINARY_API_KEY=YOUR_CLOUDINARY_API_KEY
2
3CLOUDINARY_API_SECRET=YOUR_CLOUDINARY_API_SECRET
4
5CLOUDINARY_CLOUD_NAME=YOUR_CLOUDINARY_CLOUD_NAME

Generating a Slideshow

There are two ways you can generate a slide show depending on your use case:

  1. Using a delivery URL - here you can use a template downloaded from Cloudinary to combine the relevant components in a delivery URL that looks as follows:

https://res.cloudinary.com/<cloudname>/video/upload/fn_render:<global-settings>;vars_(<slide-settings>(<individual-slide>))/<global-transformations>/<template>.<ext>

  1. Using the Upload API - this is the technique we will use in this article. We will use the create_slideshow method of the Upload API. This will create a new video in your Cloudinary account based on the parameters provided.

Multiple File Upload with Livewire

To generate a video slideshow we will need a UI (User Interface), we will use the Laravel package Livewire to build this.

  1. Install Livewire Package by running the following command in your Laravel project:

composer require livewire/livewire

  1. Include Livewire scripts and styles on every page that will be using Livewire. In our case welcome.blade.php:
1...
2
3@livewireStyles
4
5</head>
6
7<body>
8
9...
10
11@livewireScripts
12
13</body>
14
15</html>
  1. We will then create a Livewire Component to handle our image uploads:

php artisan make:livewire MultipleFileUpload

This will create two files, first app/Http/Livewire/MultipleFileUpload.php and the other one

in resources/views/livewire/multiple-file-upload.blade.php

Now you can use this component anywhere in your Laravel project using the following snippet:

<livewire:multiple-file-upload/>

or

@livewire('multiple-file-upload')

  1. Open resources/views/welcome.blade.php and add the following code within the <body></body> tags as shown below:
1<body class="antialiased">
2
3<div>
4
5@livewire('multiple-file-upload')
6
7</div>
8
9</body>

This includes the Livewire component we created earlier in our welcome.blade.php.

Note: Please ensure you go through the Livewire documentation, to learn how to install and set it up.

  1. Open the file resources/views/livewire/multiple-file-upload.blade.php and populate it with the following code:
1<form class="mb-5" wire:submit.prevent="uploadFiles">
2
3<div class="form-group row mt-5 mb-3">
4
5<div class="input-group">
6
7<input type="file" class="form-control @error('files'|'files.*') is-invalid @enderror" placeholder="Choose files..." wire:model="files" multiple>
8
9@error('files'|'files.*')
10
11<div class="invalid-feedback">{{ $message }}</div>
12
13@enderror
14
15</div>
16
17<small class="text-muted text-center mt-2" wire:loading wire:target="files">
18
19{{ __('Uploading') }}…
20
21</small>
22
23</div>
24
25<div class="text-center">
26
27<button type="submit" class="btn btn-sm btn-primary w-25">
28
29{{ __('Generate Slideshow') }}
30
31</button>
32
33</div>
34
35</form>

This is our Livewire Component view, this basically will display a form with a multiple-file input and a button.

You will see the implementation in code shortly.

Implementation in Code

Open the file app/Http/Livewire/MultipleFileUpload.php. Here, we are going to add a method that will handle the multiple files selected by the user, upload them to Cloudinary and save their public_id's in an array that we will use later on.

Add the following code to this file.

  1. First, we use Livewires WithFileUploads to help us with file uploads, then create two variables $media

and $optimizedImage which is an array that will contain the image URLs we get back from Cloudinary.

1use Livewire\WithFileUploads;
2
3public $files = [];
4
5public $slides = [];
6
7// Needed to specify the type of media file for our slideshow
8
9public $imageExt = ['jpeg', 'jpg', 'png', 'gif',];
  1. Secondly, we will create the uploadFiles function which will upload the media files to Cloudinary. We will apply specific transformations that will optimize our images for our slideshow with an aspect ratio of 9:16 which works great for most social media platforms.
1public function uploadFiles() {
2
3...
4
5}
  1. Let's populate our method in step 2 above:
1public function uploadFiles() {
2
3/* First we validate the input from the user. We will take multiple image and or video files less than 10MB in size */
4
5$this->validate([
6
7'files' => [
8
9'required',
10
11'max:102400'
12
13],
14
15'files.*' => 'mimes:jpeg,jpg,png,gif,avi,mp4,webm,mov,ogg,mkv,flv,m3u8,ts,3gp,wmv,3g2,m4v'
16
17]);
18
19/* We will now upload the media files to Cloudinary with specified transformations and get back the public_id */
20
21foreach ($this->files as $file) {
22
23$media = cloudinary()->upload($file->getRealPath(), [
24
25'folder' => 'video-slideshow',
26
27'public_id' => $file->getClientOriginalName(),
28
29'transformation' => [
30
31'aspect_ratio' => '9:16',
32
33'gravity' => 'auto', //can be face, face etc
34
35'crop' => 'fill'
36
37]
38
39])->getPublicId();
40
41/* Here we will check whether the file is an image or video from its extension and generate the appropriate media type parameter for the manifest_json */
42
43if (in_array($file->getClientOriginalExtension(), $this->imageExt)) {
44
45$this->slides[] = ['media' => 'i:'.$media];
46
47} else {
48
49$this->slides[] = ['media' => 'v:'.$media];
50
51}
52
53}
54
55/* Creating the manifest_json parameter */
56
57$manifestJson = json_encode([
58
59"w" => 540,
60
61"h" => 960,
62
63"du" => 60,
64
65"vars" => [
66
67"sdur" => 3000,
68
69"tdur" => 1500,
70
71"slides" => $this->slides,
72
73],
74
75]);
76
77/* signingData for generating the signature */
78
79$cloudName = env('CLOUDINARY_CLOUD_NAME');
80
81$timestamp = (string) Carbon::now()->unix();
82
83$signingData = [
84
85'timestamp' => $timestamp,
86
87'manifest_json' => $manifestJson,
88
89'public_id' => 'test_slideshow',
90
91'folder' => 'video-slideshow',
92
93'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
94
95];
96
97$signature = ApiUtils::signParameters($signingData, env('CLOUDINARY_API_SECRET'));
98
99/* Using Laravel Http Request to send a POST request to the create_slideshow end point */
100
101$response = Http::post("https://api.cloudinary.com/v1_1/$cloudName/video/create_slideshow", [
102
103'api_key' => env('CLOUDINARY_API_KEY'),
104
105'signature' => $signature,
106
107'timestamp' => $timestamp,
108
109'manifest_json' => $manifestJson,
110
111'resource_type' => 'video',
112
113'public_id' => 'test_slideshow',
114
115'folder' => 'video-slideshow',
116
117'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
118
119]);
120
121// Determine if the status code is >= 200 and < 300...
122
123if ($response->successful()) {
124
125session()->flash('message', 'Slideshow generated successfully!');
126
127} else {
128
129session()->flash('error', 'Slideshow generation failed! Try again later.');
130
131}
132
133}

The code above uploads the media files to Cloudinary returning their public_id's. Let's talk about the code.

  • Uploading the media files

We will get the files from user input and upload them to Cloudinary and use their public_id's to create the media type parameter media_ which will take the form media_i:<public_id> for images and media_v:<public_id> for videos.

1foreach ($this->files as $file) {
2
3$media = cloudinary()->upload($file->getRealPath(), [
4
5'folder' => 'video-slideshow',
6
7'public_id' => $file->getClientOriginalName(),
8
9'transformation' => [
10
11'aspect_ratio' => '9:16',
12
13'gravity' => 'auto', //can be face, face etc
14
15'crop' => 'fill'
16
17]])->getPublicId();
18
19
20
21if (in_array($file->getClientOriginalExtension(), $this->imageExt)) {
22
23$this->slides[] = ['media' => 'i:'.$media];
24
25} else {
26
27$this->slides[] = ['media' => 'v:'.$media];
28
29}
30
31}
  • The manifest_json parameter

The create a slideshow endpoint requires either a manifest_transformation or a manifest_json. The manifest_json parameter is a stringified json parameter, allowing you to define your slideshow settings in a structured data format, which then needs to be converted to a string.

1$manifestJson = json_encode([
2
3"w" => 540,
4
5"h" => 960,
6
7"du" => 60,
8
9"vars" => [
10
11"sdur" => 3000,
12
13"tdur" => 1500,
14
15"slides" => $this->slides,
16
17],
18
19]);

You can checkout the reference for full details on the relevant options.

  • Generating a signature

Since we are sending a request to the Cloudinary API, we need to create a signature to authenticate our request. Cloudinary SDKs automatically generate this signature for any upload or admin method that requires it. However, in this case, we are making a direct call to the REST API and we need to generate the signature.

1$cloudName = env('CLOUDINARY_CLOUD_NAME');
2
3$timestamp = (string) Carbon::now()->unix();
4
5$signingData = [
6
7'timestamp' => $timestamp,
8
9'manifest_json' => $manifestJson,
10
11'public_id' => 'test_slideshow',
12
13'folder' => 'video-slideshow',
14
15'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
16
17];
18
19
20
21$signature = ApiUtils::signParameters($signingData, env('CLOUDINARY_API_SECRET'));

The signature is a SHA-1 or SHA-256 hexadecimal message digest created based on the following parameters:

  • All parameters added to the method call should be included except : file, cloud_name, resource_type and your api_key.

  • Add the timestamp parameter.

  • Sort all the parameters in alphabetical order.

  • Separate the parameter names from their values with an = and join the parameter/value pairs together with an &.

Tip: We took a shortcut and used the Cloudinary SDK ApiUtils to create the signature:

1$signature = ApiUtils::signParameters($signingData, env('CLOUDINARY_API_SECRET'));
  • Sending the POST request to Cloudinary

With everything ready we can send the request to Cloudinary and start the video slideshow generation. We will use Laravel's Http Request based on Guzzle.

1$response = Http::post("https://api.cloudinary.com/v1_1/$cloudName/video/create_slideshow", [
2
3'api_key' => env('CLOUDINARY_API_KEY'),
4
5'signature' => $signature,
6
7'timestamp' => $timestamp,
8
9'manifest_json' => $manifestJson,
10
11'resource_type' => 'video',
12
13'public_id' => 'test_slideshow',
14
15'folder' => 'video-slideshow',
16
17'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
18
19]);

Note: Once our slideshow is ready Cloudinary will send us a Webhook notification to the notification_url.

If you successfully implemented the code above, you should be able to see the following when you navigate to http://localhost:8000:

Cloudinary Video Slideshow

Handling the Webhook Notification

Once we send the request successfully. Cloudinary will send us a pending response as it processes the generation of the video slideshow:

Cloudinary Video Slideshow Success

Cloudinary will send the following response:

1{
2
3"status": "processing",
4
5"public_id": "test_slideshow",
6
7"batch_id": "00b45635e533ab11e63585dd145ab7816ca19bff2bf3f298a0e66d87405ab7793"
8
9}

When the Cloudinary is done generating the slideshow it will send us a Webhook notification to the notification URL we provided in the request.

1{
2
3"notification_type": "upload",
4
5"timestamp": "2021-08-11T07:44:41+00:00",
6
7"request_id": "799b0f8305df4206b6d8f5dbdde0cdfc",
8
9"asset_id": "640cb419bed70ef5b86e2bbe7cbb388a",
10
11"public_id": "test_slideshow",
12
13"version": 1628667799,
14
15"version_id": "afcd9bdec6552adc43d7f316da077200",
16
17"width": 500,
18
19"height": 500,
20
21"format": "mp4",
22
23"resource_type": "video",
24
25"created_at": "2021-08-11T07:43:19Z",
26
27"tags": [],
28
29"pages": 0,
30
31"bytes": 521868,
32
33"type": "upload",
34
35"etag": "d7b3ecf1f5508af9fb8518158e78642f",
36
37"placeholder": false,
38
39"url": "http://res.cloudinary.com/demo/video/upload/v1628667799/test_slideshow.mp4",
40
41"secure_url": "https://res.cloudinary.com/demo/video/upload/v1628667799/test_slideshow.mp4",
42
43"access_mode": "public",
44
45"audio": {},
46
47"video": {
48
49"pix_format": "yuv420p",
50
51"codec": "h264",
52
53"level": 30,
54
55"profile": "High",
56
57"bit_rate": "163900",
58
59"time_base": "1/15360"
60
61},
62
63"frame_rate": 30,
64
65"bit_rate": 166997,
66
67"duration": 25,
68
69"rotation": 0,
70
71"nb_frames": 750
72
73}

We will handle this notification by creating a WebhookController.php by typing the following command:

php artisan make:controller WebhookController

In the file created app/Http/Controllers/WebhookController.php we will add the following code:

1public function cloudinary(Request $request) {
2
3//Verification
4
5$verified = SignatureVerifier::verifyNotificationSignature(json_encode($request), $request->header('X-Cld-Timestamp'), $request->header('X-Cld-Signature'));
6
7
8
9// If the signature is verified get the secure url to our slideshow
10
11if ($verified) {
12
13$secureUrl = $request->secure_url;
14
15
16
17return view('livewire.view-slideshow', ['slideshow_url' => $secureUrl]);
18
19}
20
21
22
23return response('Unverified', 401);
24
25}

Tip: A webhook is a mechanism where an application can notify another application that something has happened.

When we receive the notification from Cloudinary we can notify the user by sending them an e-mail, SMS, or push notification. It is really up to you but, in this case, we are just returning a view and passing the slideshow URL to it.

Since the notification from Cloudinary will be an external request we will need to allow it through the VerifyCsrfToken.php middleware to prevent CSRF errors.

1...
2
3protected $except = [
4
5'webhooks'
6
7];
8
9}

Next, we will create the webhook route in routes/api.php.

1...
2
3//webhooks client
4
5Route::post('webhooks/cloudinary', [WebhookController::class, 'cloudinary']);

And finally update our CLOUDINARY_NOTIFICATION_URL in the environment variables file .env as follows:

1CLOUDINARY_NOTIFICATION_URL=https://<example.com>/api/webhooks/cloudinary

Finally, we can enjoy our slideshow:

Video Slideshow

Conclusion

Yes, Cloudinary makes it easy to generate a slideshow by automating and applying some transformations. This is beautiful since it allows you to focus on other things like promoting your business with the newly created slideshow.

The possibilities are endless, check out Cloudinary for your A to Z media management - upload, storage, administration, manipulation, optimization, and delivery.

Get started with Cloudinary in your Laravel projects for FREE!

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.