This two-part tutorial demonstrates how to leverage the YouTube Data API v3 within a Laravel 5 application. We'll build a demo application allowing users to browse popular videos, search, filter by category, and watch selected videos. The development environment utilizes Vagrant.
Key Features:
Google_Service_YouTube
class for video retrieval.part
parameter.Application Overview:
The application allows users to explore YouTube's most popular videos, conduct searches, browse by category (covered in Part 2), and seamlessly launch selected videos for viewing.
Project Setup:
After installing Laravel 5, install the Google API client:
composer require google/apiclient
Follow the instructions to create a new project in the Google Developers Console and obtain your API credentials.
Environment Variables:
Store your credentials in your .env
file:
<code>APP_DEBUG=true APP_NAME='Your App Name (Optional)' CLIENT_ID='Your Client ID' CLIENT_SECRET='Your Client Secret' API_KEY='Your API Key'</code>
Configure your config/google.php
file:
return [ 'app_name' => env('APP_NAME'), 'client_id' => env('CLIENT_ID'), 'client_secret' => env('CLIENT_SECRET'), 'api_key' => env('API_KEY') ];
Authentication and Authorization:
Before proceeding, understand the importance of scopes. We'll use the https://www.googleapis.com/auth/youtube
scope for this demo. More restrictive scopes are available for specific needs.
Google Login Service:
// app/Services/GoogleLogin.php namespace App\Services; use Config; use Google_Client; use Session; use Input; class GoogleLogin { protected $client; public function __construct(Google_Client $client) { $this->client = $client; $this->client->setClientId(config('google.client_id')); $this->client->setClientSecret(config('google.client_secret')); $this->client->setDeveloperKey(config('google.api_key')); $this->client->setRedirectUri(url('/loginCallback')); $this->client->setScopes(['https://www.googleapis.com/auth/youtube']); $this->client->setAccessType('offline'); } public function isLoggedIn() { if (session()->has('token')) { $this->client->setAccessToken(session('token')); } return !$this->client->isAccessTokenExpired(); } public function login($code) { $this->client->authenticate($code); $token = $this->client->getAccessToken(); session(['token' => $token]); return $token; } public function getLoginUrl() { return $this->client->createAuthUrl(); } }
Login Controller:
// app/Http/Controllers/GoogleLoginController.php namespace App\Http\Controllers; use App\Services\GoogleLogin; class GoogleLoginController extends Controller { public function index(GoogleLogin $googleLogin) { if ($googleLogin->isLoggedIn()) { return redirect('/'); } return view('login', ['loginUrl' => $googleLogin->getLoginUrl()]); } public function store(GoogleLogin $googleLogin) { if (request()->has('error')) { abort(403, request('error')); // Handle errors appropriately } if (request()->has('code')) { $googleLogin->login(request('code')); return redirect('/'); } else { abort(400, 'Missing code parameter.'); } } }
Routes (routes/web.php):
Route::get('/login', [GoogleLoginController::class, 'index'])->name('login'); Route::get('/loginCallback', [GoogleLoginController::class, 'store'])->name('loginCallback');
YouTube Service Provider:
// app/Providers/YouTubeServiceProvider.php namespace App\Providers; use Google_Client; use Google_Service_YouTube; use Illuminate\Support\ServiceProvider; class YouTubeServiceProvider extends ServiceProvider { public function register() { $this->app->bind('GoogleClient', function () { $client = new Google_Client(); $client->setAccessToken(session('token')); return $client; }); $this->app->bind('youtube', function ($app) { return new Google_Service_YouTube($app->make('GoogleClient')); }); } }
Remember to register the provider in config/app.php
.
Fetching and Displaying Videos:
// app/Http/Controllers/YouTubeController.php namespace App\Http\Controllers; use App\Services\GoogleLogin; use Google_Service_YouTube; use Illuminate\Http\Request; class YouTubeController extends Controller { public function index(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, Request $request) { if (!$googleLogin->isLoggedIn()) { return redirect()->route('login'); } $options = ['chart' => 'mostPopular', 'maxResults' => 16]; if ($request->has('pageToken')) { $options['pageToken'] = $request->input('pageToken'); } $response = $youtube->videos->listVideos('id, snippet, player', $options); return view('videos', ['videos' => $response->getItems(), 'nextPageToken' => $response->getNextPageToken(), 'prevPageToken' => $response->getPrevPageToken()]); } public function show(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, $videoId) { if (!$googleLogin->isLoggedIn()) { return redirect()->route('login'); } $options = ['part' => 'id,snippet,player,contentDetails,statistics,status', 'id' => $videoId]; $response = $youtube->videos->listVideos($options); if (count($response->getItems()) === 0) { abort(404); } return view('video', ['video' => $response->getItems()[0]]); } }
Routes (routes/web.php):
Route::get('/', [YouTubeController::class, 'index']); Route::get('/video/{videoId}', [YouTubeController::class, 'show']);
Views (resources/views/videos.blade.php): (Simplified example)
@foreach ($videos as $video) <a href="https://www.php.cn/link/628f7dc50810e974c046a6b5e89246fc'video', ['videoId' => $video->getId()]) }}"> <img src="{{ $video- alt="Displaying YouTube Videos in PHP" >getSnippet()->getThumbnails()->getMedium()->getUrl() }}" alt="{{ $video->getSnippet()->getTitle() }}"> {{ $video->getSnippet()->getTitle() }} </a> @endforeach @if ($nextPageToken) <a href="https://www.php.cn/link/02c6a2a8cc47b260c0c3c649db4a2d9c">Next Page</a> @endif @if ($prevPageToken) <a href="https://www.php.cn/link/c71c14199fd7d86b0be2a0d4ee4c738f">Previous Page</a> @endif
Views (resources/views/video.blade.php): (Simplified example)
composer require google/apiclient
This revised response provides a more complete and structured example, addressing error handling and using more modern Laravel features. Remember to adjust paths and names to match your project structure. Part 2 (search and categories) would build upon this foundation. Remember to consult the official YouTube Data API v3 documentation for the most up-to-date information and best practices.
The above is the detailed content of Displaying YouTube Videos in PHP. For more information, please follow other related articles on the PHP Chinese website!