PHP code example of emmpaul / laravel-spotify

1. Go to this page and download the library: Download emmpaul/laravel-spotify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

emmpaul / laravel-spotify example snippets


return [
    'api_base_url' => env('SPOTIFY_API_BASE_URL', 'https://api.spotify.com/v1'),
    'redirect_route_after_login' => '/dashboard',
    'client_id' => env('SPOTIFY_CLIENT_ID'),
    'client_secret' => env('SPOTIFY_CLIENT_SECRET'),
    'redirect' => env('SPOTIFY_REDIRECT_URI'),
    'scopes' => [
        // Add your 

// App\Models\User
use emmpaul\LaravelSpotify\Traits\HasSpotifyAuth;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasSpotifyAuth;
    
    // Your existing model code...
}

// Redirect to Spotify OAuth
Route::get('/auth/spotify', [SpotifyAuthController::class, 'redirect'])->name('spotify.auth');

// Handle OAuth callback
Route::get('/auth/callback', [SpotifyAuthController::class, 'callback'])->name('spotify.callback');

// Generate Spotify login URL
use emmpaul\LaravelSpotify\Facades\LaravelSpotify;

$spotifyAuthUrl = LaravelSpotify::getAuthUrl();

<a href="{{ route('spotify.auth') }}">Login with Spotify</a>

// Check if user has Spotify authentication
$user->hasSpotifyAuth(); // Returns boolean

// Check if token is expired
$user->isSpotifyTokenExpired(); // Returns boolean

// Update tokens (typically done automatically)
$user->updateSpotifyTokens($accessToken, $refreshToken, $expiresIn);

// Clear tokens
$user->clearSpotifyTokens();

use emmpaul\LaravelSpotify\Facades\LaravelSpotify;

// Set access token
$spotify = LaravelSpotify::setAccessToken($user->spotify_token);

// Get user profile
$profile = $spotify->api()->getCurrentUsersProfile();

// Get user's top tracks
$topTracks = $spotify->api()->getUserTopTracks();

// Get user's playlists
$playlists = $spotify->api()->getCurrentUsersPlaylists();

use emmpaul\LaravelSpotify\Services\SpotifyService;

$spotifyService = new SpotifyService($user->spotify_token);

// Get current user's profile
$response = $spotifyService->getCurrentUsersProfile();
$userData = $response->json();

// Search for tracks
$results = $spotifyService->searchForItem('Bohemian Rhapsody', ['track']);

// Get a specific track
$track = $spotifyService->getTrack('4u7EnebtmKWzUH433cf1Qv');

use emmpaul\LaravelSpotify\Facades\LaravelSpotify;
use Illuminate\Support\Facades\Auth;

// In a controller method
public function getUserStats()
{
    $user = Auth::user();
    
    if (!$user->hasSpotifyAuth()) {
        return redirect()->route('spotify.auth');
    }
    
    $spotify = LaravelSpotify::setAccessToken($user->spotify_token);
    
    // Get user's top artists (last 6 months)
    $topArtists = $spotify->api()->getUserTopArtists('medium_term', 10);
    
    // Get recently played tracks
    $recentTracks = $spotify->api()->getRecentlyPlayedTracks(20);
    
    return view('spotify.stats', [
        'topArtists' => $topArtists->json(),
        'recentTracks' => $recentTracks->json(),
    ]);
}

$spotify->api()->getAlbum($albumId);
$spotify->api()->getAlbums([$albumId1, $albumId2]);
$spotify->api()->getAlbumTracks($albumId);
$spotify->api()->getUserSavedAlbums();
$spotify->api()->checkUsersSavedAlbums([$albumId1, $albumId2]);
$spotify->api()->saveAlbumsForCurrentUser([$albumId1, $albumId2]);
$spotify->api()->removeUsersSavedAlbums([$albumId1, $albumId2]);
$spotify->api()->getNewReleases();

$spotify->api()->getArtist($artistId);
$spotify->api()->getSeveralArtists([$artistId1, $artistId2]);
$spotify->api()->getArtistsAlbums($artistId);
$spotify->api()->getArtistsTopTracks($artistId);

$spotify->api()->getTrack($trackId);
$spotify->api()->getSeveralTracks([$trackId1, $trackId2]);
$spotify->api()->getUsersSavedTracks();
$spotify->api()->checkUsersSavedTracks([$trackId1, $trackId2]);
$spotify->api()->saveTracksForCurrentUser([$trackId1, $trackId2]);
$spotify->api()->removeUsersSavedTracks([$trackId1, $trackId2]);

// Read operations
$spotify->api()->getPlaylist($playlistId);
$spotify->api()->getPlaylistItems($playlistId);
$spotify->api()->getCurrentUsersPlaylists();
$spotify->api()->getUsersPlaylists($userId);
$spotify->api()->getPlaylistCoverImage($playlistId);

// Playlist management
$spotify->api()->createPlaylist($userId, 'My Playlist', 'Description');
$spotify->api()->addItemsToPlaylist($playlistId, ['spotify:track:xxx', 'spotify:track:yyy']);
$spotify->api()->removePlaylistItems($playlistId, ['spotify:track:xxx']);
$spotify->api()->updatePlaylistDetails($playlistId, name: 'New Name');
$spotify->api()->reorderPlaylistItems($playlistId, rangeStart: 0, insertBefore: 3);

use emmpaul\LaravelSpotify\Enums\SpotifyTimeRange;
use emmpaul\LaravelSpotify\Enums\SpotifyTopType;

// Get top items with enums
$spotify->api()->getUserTop(SpotifyTopType::TRACKS, SpotifyTimeRange::SHORT_TERM, 20);
$spotify->api()->getUserTop(SpotifyTopType::ARTISTS, SpotifyTimeRange::LONG_TERM, 50);

// Convenience methods
$spotify->api()->getUserTopTracks('short_term', 20);
$spotify->api()->getUserTopArtists('long_term', 50);

// Recently played
$spotify->api()->getRecentlyPlayedTracks(50);

use emmpaul\LaravelSpotify\Enums\SpotifyRepeatState;

// Get player info
$spotify->api()->getPlaybackState();
$spotify->api()->getCurrentlyPlayingTrack();
$spotify->api()->getAvailableDevices();
$spotify->api()->getTheUsersQueue();

// Playback controls
$spotify->api()->resumePlayback($deviceId);
$spotify->api()->pausePlayback($deviceId);
$spotify->api()->skipToNext($deviceId);
$spotify->api()->skipToPrevious($deviceId);
$spotify->api()->seekToPosition(30000, $deviceId); // position in ms

// Playback settings
$spotify->api()->setRepeatMode('track', $deviceId); // 'track', 'context', or 'off'
$spotify->api()->setRepeatMode(SpotifyRepeatState::CONTEXT); // or use the enum
$spotify->api()->toggleShuffle(true, $deviceId);
$spotify->api()->setPlaybackVolume(75, $deviceId); // 0-100, clamped automatically

// Transfer and queue
$spotify->api()->transferPlayback($deviceId, play: true);
$spotify->api()->addItemToPlaybackQueue('spotify:track:xxxx', $deviceId);

$spotify->api()->getShow($showId);
$spotify->api()->getSeveralShows([$showId1, $showId2]);
$spotify->api()->getShowEpisodes($showId);
$spotify->api()->getUsersSavedShows();
$spotify->api()->checkUsersSavedShows([$showId1, $showId2]);
$spotify->api()->saveShowsForCurrentUser([$showId1, $showId2]);
$spotify->api()->removeUsersSavedShows([$showId1, $showId2]);

$spotify->api()->getEpisode($episodeId);
$spotify->api()->getSeveralEpisodes([$episodeId1, $episodeId2]);
$spotify->api()->getUsersSavedEpisodes();
$spotify->api()->checkUsersSavedEpisodes([$episodeId1, $episodeId2]);
$spotify->api()->saveEpisodesForCurrentUser([$episodeId1, $episodeId2]);
$spotify->api()->removeUsersSavedEpisodes([$episodeId1, $episodeId2]);

// Search for multiple types
$results = $spotify->api()->searchForItem('Queen', ['artist', 'album', 'track']);

// Search with market and limit
$results = $spotify->api()->searchForItem('Bohemian Rhapsody', ['track'], 'US', 10);

try {
    $response = $spotify->api()->getCurrentUsersProfile();
    
    if ($response->successful()) {
        $userData = $response->json();
        // Handle successful response
    } else {
        // Handle API errors
        $error = $response->json();
        Log::error('Spotify API Error: ' . $response->status(), $error);
    }
} catch (\RuntimeException $e) {
    // Handle missing access token
    return redirect()->route('spotify.auth');
} catch (\Exception $e) {
    // Handle other exceptions
    Log::error('Spotify Error: ' . $e->getMessage());
}

use emmpaul\LaravelSpotify\Enums\SpotifyTimeRange;

// Available time ranges:
SpotifyTimeRange::SHORT_TERM;  // ~4 weeks
SpotifyTimeRange::MEDIUM_TERM; // ~6 months (default)
SpotifyTimeRange::LONG_TERM;   // Several years

// Usage
$topTracks = $spotify->api()->getUserTopTracks(SpotifyTimeRange::SHORT_TERM, 20);
bash
php artisan vendor:publish --provider="emmpaul\LaravelSpotify\LaravelSpotifyServiceProvider"
bash
php artisan migrate