How to Upload Video on YouTube in Laravel Application

Recently one of our readers asked how to upload a video on YouTube from the Laravel application. They wanted to build a system to upload YouTube videos from within the Laravel application. By creating this system, they don’t need to share access to the YouTube account with the team members who manage the videos.

I have already written an article on uploading a video on YouTube using YouTube API in PHP. In this article, we will study how to upload a video on YouTube from the Laravel application.

To get started, you must have a Google Account. On the Google account, you need to register the application and get the API keys.

Register an Application and Get Credentials

Below are the steps to register an application and grab the API keys.

  • Go to the Google Developer Console.
  • Create a new project. You can also select the existing project.
  • Type the name of your project. Google Console will create a unique project ID for you.
  • Upon creating a project, it will appear on top of the left sidebar.
  • Click on Library from the left menu. You will see a list of Google APIs. Enable the YouTube Data API.
  • Next, from the left menu click on the Credentials. Select Oauth Client id under Create credentials. Choose the radio button for the Web Application.
  • Give the Name. Under Authorized JavaScript origins enter your domain URL. In the Authorized redirect URIs add the link of the redirect URL as http://localhost:8000/youtube/callback. I am passing my local URL here. You should adjust this URL with your domain.
  • Finally, click on the Create button. You will get a client ID and client secret. Copy these details for later use.
Google Application

Install and Configure GitHub Library

Once you created the application, install the joedawson/youtube library to your Laravel project. Open the terminal in your project root directory and run the command:

composer require dawson/youtube

After installing the library, register the service provider and aliases in the config/app.php file.

....
'providers' => ServiceProvider::defaultProviders()->merge([
    ...
    Dawson\Youtube\YoutubeServiceProvider::class,
])->toArray(),
....
'aliases' => Facade::defaultAliases()->merge([
    ....
    'Youtube' => Dawson\Youtube\Facades\Youtube::class,
])->toArray(),

Next, publish the configuration using the below command:

php artisan vendor:publish --provider="Dawson\Youtube\YoutubeServiceProvider"

The above command creates the migration and config/youtube.php file. Now, run the migration command which will create a table youtube_access_tokens in the database.

php artisan migrate

The youtube_access_tokens table would store the access token after authorizing the YouTube account. The access token is required when you interact with the YouTube API. This token acts as an identifier for your YouTube account. However, the access token has a short span of a lifetime. Under the hood, to get the new access token this library uses a refresh token. You don’t need to worry about inserting these tokens into a table. The library will perform these operations in the background.

You have copied the Google API credentials that need to be put inside the Laravel application. Open the .env file and add your client id and client secret as follows:

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

When you are making any changes in the environment file, you probably need to clear the configuration cache using the command:

php artisan config:clear

Authorization of Google Account

You can now authorize a YouTube account by running the YOUR_DOMAIN_URL/youtube/auth URL in the browser. It will redirect to the Google login page to authenticate your account. Complete the process. On successful authentication, you will redirect back to your Laravel application. Check the youtube_access_tokens table and you should see tokens inserted in the access_token column. This is a one-time process. The library will automatically generate a new token in the background even if it is expired. The user does not need to authorize their account again.

Upload Video on YouTube Account in Laravel Application

At this stage, you are ready with the access token. Now create a form to browse the video file and send it to YouTube. Let’s create a controller by running the below command.

php artisan make:controller VideoController --resource

Define the routes for VideoController as follows.

Route::resource('video', 'VideoController');

Create a resources/views/video.blade.php and add the below code in it.

<form action="{{ url('video') }}" method="post" enctype="multipart/form-data">
    @csrf
    <p><input type="text" name="title" placeholder="Enter Video Title" /></p>
    <p><textarea name="description" cols="30" rows="10" placeholder="Video description"></textarea></p>
    <p><input type="file" name="video" /></p>
    <button type="submit" name="submit">Submit</button>
</form>

Call this view from the index() method of VideoController.

public function index()
{
    return view('video');
}

Now, when you visit YOUR_DOMAIN_URL/video you will see a form that contains file input, title, description, and submit button.

In order to call the YouTube API add a Youtube facade to a VideoController. And in the store() method write the code for uploading a video on YouTube as follows.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Youtube;
 
class VideoController extends Controller
{
    ....
    public function store(Request $request)
    {
        $video = Youtube::upload($request->file('video')->getPathName(), [
            'title'       => $request->input('title'),
            'description' => $request->input('description')
        ]);
 
        return "Video is uploaded successfully. Video ID is ". $video->getVideoId();
    }
}

Here we are passing a video file, title, and description from the HTML form. This code simply uploads your video on YouTube and prints the YouTube video id.

Upload a Custom Thumbnail on YouTube Video

If you want to upload a custom thumbnail for the YouTube video, you need to verify the phone number with your YouTube account. Visit the link https://www.youtube.com/features for the phone number verification.

Upon verifying the phone number, you can add one more file input for the image on a previous form.

<p>Video Thumbnail: <input type="file" name="image" /></p>

Make sure you are uploading an image with the standard size 1280x720 defined for the YouTube thumbnail. This image will then send along with other details as follows.

$video = Youtube::upload($request->file('video')->getPathName(), [
    'title'       => $request->input('title'),
    'description' => $request->input('description')
])->withThumbnail($request->file('image')->getPathName());

For deleting a video, just pass the video id to the delete() method as shown below.

Youtube::delete('VIDEO_ID');

I hope you understand about uploading a video on YouTube in the Laravel application. This tutorial should help you to manage YouTube videos within your Laravel website.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

22 thoughts on “How to Upload Video on YouTube in Laravel Application

  1. – upload video throw errror .how to solved
    { “error”: { “code”: 403, “message”: “The request cannot be completed because you have exceeded your \u003ca href=\”/youtube/v3/getting-started#quota\”\u003equota\u003c/a\u003e.”, “errors”: [ { “message”: “The request cannot be completed because you have exceeded your \u003ca href=\”/youtube/v3/getting-started#quota\”\u003equota\u003c/a\u003e.”, “domain”: “youtube.quota”, “reason”: “quotaExceeded” } ] } }

  2. { “error”: { “code”: 403, “message”: “The request cannot be completed because you have exceeded your \u003ca href=\”/youtube/v3/getting-started#quota\”\u003equota\u003c/a\u003e.”, “errors”: [ { “message”: “The request cannot be completed because you have exceeded your \u003ca href=\”/youtube/v3/getting-started#quota\”\u003equota\u003c/a\u003e.”, “domain”: “youtube.quota”, “reason”: “quotaExceeded” } ] } }

  3. when i you yours define route Route::resource(‘videos’, ‘VideoController’);
    it give me error
    Target class [VideoController] does not exist.
    and when you use Route::post(‘/videos’, [App\Http\Controllers\VideoController::class, ‘index’])->name(‘pages.videos’);
    it does not upload video and return back to videos page

    1. Error: Target class [VideoController] does not exist.
      Fix: Enable namespace protected $namespace = 'App\\Http\\Controllers'; in \app\Providers\RouteServiceProvider.php.

      1. after update name sepace and using your route code now give me error
        implode(): Argument #2 ($array) must be of type ?array, string given
        file error
        :\Users\muhaf\blog\vendor\google\apiclient\src\Google\Http\REST.php:173

          1. implode(): Argument #2 ($array) must be of type ?array, string given same error after creating new project copy each step of your video and blog

          2. after update name sepace and using your route code now give me error
            implode(): Argument #2 ($array) must be of type ?array, string given
            file error
            :\Users\muhaf\blog\vendor\google\apiclient\src\Google\Http\REST.php:173

            Reply
            same error after recreating new project.

  4. hello

    getting below error.

    # php artisan cache:clear
    PHP Fatal error: Uncaught Error: Class ‘Illuminate\Foundation\Application’ not found in /var/www/html/bootstrap/app.php:14
    Stack trace:
    #0 /var/www/html/artisan(20): require_once()
    #1 {main}
    thrown in /var/www/html/bootstrap/app.php on line 14

  5. hello Friend

    can you please help .
    I am fetching my video details from DB rather using any form. Also my data is on s3. how can I write controller function so that I can get multiple video & details from mysql and upload those videos to youtube.?
    Can you please help me how it can be done without form?

    ‘DB::table(‘clips’)->select(‘video’)->where(‘private’, 0)->where(‘syncchannel’, 1);’
    $description => ‘DB::table(‘clips’)->select(‘description’)->where(‘private’, 0)->where(‘syncchannel’, 1);’
    $title => ‘DB::table(‘users’)->select(‘name’);’
    ]);

    return $video->getVideoId();

  6. I have used this package and working fine for me. But, I need to specify the channel for every video that in which channel it should be uploaded. Is there any way, where I can specify channel ID or something to upload video to specific YouTube channel?

  7. sir, I follow your code
    (1/1) BindingResolutionException
    Target [Dawson\Youtube\Contracts\Youtube] is not instantiable.
    This error occurred please tell me how to do it? because I am new in Laravel

  8. Sir… i used your code An Api but one problem issue one error so how can solve this problem this error (An token is rquired ) sir. plz help me

    1. Did you run YOUR_DOMAIN_URL/youtube/auth in the browser? You need to authorize Google account first. This link will redirect you to Google account and authorize you to generate an access token.

Leave a Reply

Your email address will not be published. Required fields are marked *