Skip to content

Compressing, Resizing, and Optimizing Videos in Laravel

Videos are large media files—in most cases, at least four times larger than images—and are often created for ads, marketing campaigns, and instructional content to convey as much information as possible in a short time. Ensuring that videos do not buffer all the time and that the user’s data is protected from rapid consumption due to heavy page weight must be the modus operandi for all website builders and e-business owners.

This article shows you how to optimize videos in Laravel.

1. Install Composer and PHP on your development or production machine and then run this command:

composer create-project --prefer-dist laravel/laravel video-optimization

2. Go to the video-optimization directory and rename the env.example file to .env.

3. Run the project with the command php artisan serve.

Your Laravel project is now up and running.

With Cloudinary, you can efficiently optimize media assets—regardless of programming language. One reason is that, by default, Cloudinary automatically performs certain optimization steps on all transformed images. Plus, its integrated, fast-delivery capability through content delivery networks (CDNs) ensures that your images are seamlessly displayed on your viewers’ devices.

To enable video uploads and optimization with Cloudinary:

  1. Sign up for a free Cloudinary account, log in, and note your cloud name and API keys from the dashboard.

    media library

  2. Install Cloudinary’s Laravel SDK:

composer require cloudinary-labs/cloudinary-laravel

Important: Be sure to follow the steps in the #Installation section. Publish the configuration file and add your Cloudinary credentials to the .env file of your app.

1. Create a video-upload controller (VideoUpload Controller) in your project:

php artisan make:controller VideoUploadController
Code language: CSS (css)

2. Open the VideoUploadController.php file and add a method for displaying the upload form:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class VideoUploadController extends Controller { public function showUploadForm() { return view('upload'); } }
Code language: HTML, XML (xml)

3. Create an upload.blade.php file in the resources/views directory and populate the file with the code below:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel Video Upload</title> <!-- Fonts --> <link href=",600" rel="stylesheet"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Nunito', sans-serif; font-weight: 200; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 13px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> <div class="content"> <div class="title m-b-md"> Laravel File Upload </div> @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <div class="links"> <form action="/upload" method="POST" enctype="multipart/form-data"> @csrf <div class="row"> <div class="col-md-6"> <input type="file" name="video" class="form-control"> </div> <div class="col-md-6"> <button type="submit" class="btn btn-success">Upload a Video</button> </div> </div> </form> </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

On a successful upload, the code above displays the form along with a confirmation message. Concurrently, the code posts the form data to an /upload route in the routes/web.php file.


You’ll see the related code later in this post.

4. Go to the routes/web.php directory and add two routes: one to display the form and the other to process the file upload:

Route::get('/upload', 'VideoUploadController@showUploadForm'); Route::post('/upload', 'VideoUploadController@storeUploads');
Code language: PHP (php)

Now reload the app and go to the /upload route. This page is then displayed:

Laravel File upload

Create an upload method in the VideoUploadController.php file to ensure that compression and resizing of user-uploaded images occur by default on upload.

The code below resizes a video to 350 pixels in width and 200 pixels in height:

public function upload(Request $request) { $resizedVideo = cloudinary()->uploadVideo($request->file('video')->getRealPath(), [ 'folder' => 'uploads', 'transformation' => [ 'width' => 350, 'height' => 200 ] ])->getSecurePath(); dd($resizedVideo); }
Code language: PHP (php)

To consistently deliver the highest-quality videos with the smallest file sizes, follow the steps below.

Compress and optimize the quality of a video file with the code below:

public function upload(Request $request) { $compressedVideo = cloudinary()->upload($request->file('video')->getRealPath(), [ 'folder' => 'uploads', 'transformation' => [ 'quality' => auto, ] ])->getSecurePath(); dd($resizedVideo); }
Code language: PHP (php)

Setting the auto value for the quality attributes automatically compresses and optimizes the video, balancing its visual quality. You can specify any of the auto options below:

  • q_auto: The optimal balance between the file size and visual quality. By default, this algorithm is the same as q_auto:good.
  • q_auto:best: A less aggressive algorithm that generates bigger files with potentially higher visual quality.
  • q_auto:good: An algorithm that ensures a relatively small file size with good visual quality.
  • q_auto:eco: A more aggressive algorithm, which results in smaller files of slightly lower visual quality. Examples of the target audience are popular sites and social networks with heavy traffic.
  • q_auto:low: The most aggressive algorithm, which results in the smallest files of low visual quality. Examples of the target audience are sites with thumbnail previews that link to higher-quality videos.

As an illustration, here’s the original, uncompressed video with a size of 8.3 MB:

Here’s the compressed version with a size of 5.9 MB:

Visually, there’s almost no difference between the two videos even though the second one is only slightly more than half the size of the first one.

Compress and optimize the video file by selecting the best video format for delivery on the client:

public function upload(Request $request) { $compressedVideo = cloudinary()->upload($request->file('video')->getRealPath(), [ 'folder' => 'uploads', 'transformation' => [ 'fetch_format' => auto, ] ])->getSecurePath(); dd($resizedVideo); }
Code language: PHP (php)

Setting fetch_format to auto instructs Cloudinary to deliver the best format that saves bandwidth and to optimize delivery time by selecting the appropriate format and codec based on the browser or client that requests the video. For instance, Chrome would attempt to deliver a VP9-encoded WebM file; Safari, an HEVC-encoded MP4 file. Other browsers would attempt to deliver an H.264-encoded MP4 file, especially if they don’t support the first two types of video encoding that work on Chrome and Safari.

You can continuously optimize video quality during streaming with the adaptive bitrate (ABR) delivery technique, which adjusts the quality of a video stream in real time according to the detected bandwidth and CPU capacity. That way, videos can start faster with fewer buffering interruptions and with the highest quality for the current device and network connection, resulting in an optimal user experience.

Furthermore, Cloudinary can automatically generate and deliver all those files from a single original video, transcoded to either or both of these two protocols:

  • HTTP Live Streaming (HLS)
  • Dynamic Adaptive Streaming over HTTP (MPEG-DASH)

For details on how to optimize videos with the ABR technique, see the Cloudinary Adaptive Streaming Guide.

Cloudinary helps you administer the entire spectrum of your media’s lifecycle, end to end, from upload and transformation to optimization and delivery. Do check it out.

Back to top

Featured Post