In today's digital age, YouTube has become a dominant platform for video content. Understanding the metrics behind a YouTube channel can provide valuable insights for content creators, marketers, and analysts. One such metric is the number of subscribers a channel has.
Add to the .env your Youtube channel ID and API key.
YOUTUBE_API_KEY=YOUR_CHANNEL_ID
YOUTUBE_CHANNEL_ID=API_KEY
Add youtube credentials into config
'youtube' => [
'api_key' => env('YOUTUBE_API_KEY', ''),
'channel_id' => env('YOUTUBE_CHANNEL_ID', ''),
],
Create console class for getting number of subscribers
<?php
namespace App\Console\Commands\Youtube;
use App\Models\SocialCount;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Cache\Repository as Cache;
class YoutubeCountConsole extends Command
{
/**
* @var string
*/
protected $signature = 'youtube:count';
/**
* @var string
*/
protected $description = '';
/**
* @return void
*/
public function handle(Cache $cache)
{
// Credential
$youtubeChannelId = config('services.youtube.channel_id');
$youtubeApiKey = config('services.youtube.api_key');
// HTTP CLient
$response = Http::get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'statistics',
'fields' => 'items/statistics/subscriberCount',
'id' => $youtubeChannelId,
'key' => $youtubeApiKey,
]);
//
if ($response->successful()) {
// Response
$json = $response->json();
/* Data */
$count = $json['items'][0]['statistics']['subscriberCount'];
echo $count . "\n";
} else {
echo $response->body() . "\n";
}
}
}