A comprehensive Laravel package that provides Spotify OAuth authentication and a complete wrapper around the Spotify Web API.
- 🔐 OAuth Authentication: Seamless Spotify OAuth integration with user management
- 🎵 Complete API Wrapper: Full access to Spotify Web API endpoints
- 👤 User Integration: Trait-based user model extension with token management
- 🎯 Type Safety: Enums for time ranges and data types
You can install the package via composer:
composer require emmpaul/laravel-spotifyYou can publish the config and migrations with:
php artisan vendor:publish --provider="emmpaul\LaravelSpotify\LaravelSpotifyServiceProvider"Then run the migrations:
php artisan migrateAdd the following environment variables to your .env file:
SPOTIFY_CLIENT_ID=your_spotify_client_id
SPOTIFY_CLIENT_SECRET=your_spotify_client_secret
SPOTIFY_REDIRECT_URI=SPOTIFY_REDIRECT_URI needs to match the redirect URI you set in your Spotify app.
This is the contents of the published config file:
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 required scopes here
],
];Note: Customize the
redirect_route_after_loginandscopesto match your application needs.
Add the HasSpotifyAuth trait to your User model:
// 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...
}The package automatically registers the following routes:
// 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');In your view or controller:
// Generate Spotify login URL
use emmpaul\LaravelSpotify\Facades\LaravelSpotify;
$spotifyAuthUrl = LaravelSpotify::getAuthUrl();Or use the named route:
<a href="{{ route('spotify.auth') }}">Login with Spotify</a>The HasSpotifyAuth trait provides several helpful methods:
// 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()->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()->getPlaylist($playlistId);
$spotify->api()->getPlaylistItems($playlistId);
$spotify->api()->getCurrentUsersPlaylists();
$spotify->api()->getUsersPlaylists($userId);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);$spotify->api()->getPlaybackState();
$spotify->api()->getCurrentlyPlayingTrack();
$spotify->api()->getAvailableDevices();
$spotify->api()->getTheUsersQueue();// 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 the SpotifyTimeRange enum for top tracks/artists:
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);composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.