Home » Laravel Video Upload Tutorial With Example

Laravel Video Upload Tutorial With Example

Last updated on May 28, 2022 by

We will see the Laravel video upload tutorial with an example in this post. We can easily upload different types of videos like .3gp, .mov, .mp4, .avi, etc. using the Laravel video upload form. We will add the validation rules to only allow particular video formats in the Laravel for better security. Let’s just dive into it.

Step 1: Install Laravel

If you already have installed Laravel on your local machine then you can skip this step. You can easily install the fresh version of Laravel by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app.

composer create-project --prefer-dist laravel/laravel demo-app

Step 2: Create Migrations

In the demo-app project create a migration to create a videos table to store uploaded video path & title.

cd demo-app
php artisan make:migration create_videos_table --create=videos

After running the above command a new migration file will be created in /demo-app/database/migration/2022_05_22_000000_create_videos_table.php

Now, let’s add the title & path fields into the videos table as below:

<?php

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

class CreateVideosTable extends Migration
{
    public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('path');
            $table->timestamps();
        });
    }

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

Now, we need to populate the database with the newly created table. To do so, run the below command:

php artisan migrate

Or you can run the below command to drop all the tables and repopulate it:

php artisan migrate:fresh

Step 3: Create A Model

In this step, we will create a Video model which helps us to connect with the videos table so that we can perform the database operations using the model. Run the below command to create a model.

php artisan make:model Video

Then the new file will be created in demo-app/app/Models/Video.php. In the model add the path and title fields in the fillable array.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'path'
    ];
}

Step 4: Create VideoController

Let’s create a VideoController and let’s add two methods, one for the display upload form and the second for the store videos.

app/Http/Controllers/FileUploadController.php

<?php

namespace App\Http\Controllers;

use App\Models\Video;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class VideoController extends Controller
{
    public function getVideoUploadForm()
    {
        return view('video-upload');
    }

    public function uploadVideo(Request $request)
   {
        $this->validate($request, [
            'title' => 'required|string|max:255',
            'video' => 'required|file|mimetypes:video/mp4',
        ]);

        $fileName = $request->video->getClientOriginalName();
        $filePath = 'videos/' . $fileName;

        $isFileUploaded = Storage::disk('public')->put($filePath, file_get_contents($request->video));

        // File URL to access the video in frontend
        $url = Storage::disk('public')->url($filePath);

        if ($isFileUploaded) {
            $video = new Video();
            $video->title = $request->title;
            $video->path = $filePath;
            $video->save();

            return back()
            ->with('success','Video has been successfully uploaded.');
        }

        return back()
            ->with('error','Unexpected error occured');
    }
}

Video MIME types

Use the following MIME types for validating another video type:

Video TypeExtensionMIME Type
Flash.flvvideo/x-flv
MPEG-4.mp4video/mp4
iPhone Index.m3u8application/x-mpegURL
iPhone Segment.tsvideo/MP2T
3GP Mobile.3gpvideo/3gpp
QuickTime.movvideo/quicktime
A/V Interleave.avivideo/x-msvideo
Windows Media.wmvvideo/x-ms-wmv

Step 5: Create Routes

We need to add two routes in routes/web.php file to perform the Laravel video upload form. The first GET route is to show the video upload form and another route for the POST method to store the video file in Laravel.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\VideoController;


Route::get('video-upload', [ VideoController::class, 'getVideoUploadForm' ])->name('get.video.upload');
Route::post('video-upload', [ VideoController::class, 'uploadVideo' ])->name('store.video');

Step 6: Create Blade/HTML File

At last, we need to create a video-upload.blade.php file in the views folder and in this file, we will add the video upload Form HTML.

<!DOCTYPE html>
<html>
   <head>
      <title>Laravel Video Upload Form - ScratchCode.io</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container mt-5">
         <div class="panel panel-primary">
            <div class="panel-heading">
               <h2>Laravel Video Upload Form- ScratchCode.io</h2>
            </div>
            <div class="panel-body">
               @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

               @if (count($errors) > 0)
               <div class="alert alert-danger">
                  <strong>Whoops!</strong> There were some problems with your input.
                  <ul>
                     @foreach ($errors->all() as $error)
                     <li>{{ $error }}</li>
                     @endforeach
                  </ul>
               </div>
               @endif

               <form action="{{ route('store.video') }}" method="POST" enctype="multipart/form-data">
                  @csrf
                  <div class="row">

                     <div class="col-md-12">
                        <div class="col-md-6 form-group">
                           <label>Title:</label>
                           <input type="text" name="title" class="form-control"/>
                        </div>
                        <div class="col-md-6 form-group">
                           <label>Select Video:</label>
                           <input type="file" name="video" class="form-control"/>
                        </div>
                        <div class="col-md-6 form-group">
                           <button type="submit" class="btn btn-success">Save</button>
                        </div>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

Step 7: Output

Hurray! We have completed all steps for the Laravel video upload form. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/video-upload
laravel video upload form step by step tutorial with example
laravel video upload success message step by step tutorial with example

Notes: You can find the uploaded file in storage/app/public/videos the directory. Please note that the storage public folder is publicly available so if you want to keep videos private then use the “local” disk driver like Storage::disk('public')

laravel video upload step by step tutorial with example
laravel video upload step by step tutorial with example

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. Laravel Upload File To AWS s3 Bucket Tutorial Example
  16. Git Permission Denied Public Key Quick Fix
  17. Laravel Run Specific Migration
  18. Laravel File Upload Form Tutorial With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to learn the Laravel video upload form tutorial with the example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment