PHPackages                             emmpaul/laravel-spotify - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. emmpaul/laravel-spotify

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

emmpaul/laravel-spotify
=======================

This is a package that adds authentification via Spotify. It also adds a wrapper around the spotify api

v1.3.0(2mo ago)1671[2 PRs](https://github.com/emmpaul/laravel-spotify/pulls)MITPHPPHP ^8.4CI passing

Since Sep 8Pushed 1mo agoCompare

[ Source](https://github.com/emmpaul/laravel-spotify)[ Packagist](https://packagist.org/packages/emmpaul/laravel-spotify)[ Docs](https://github.com/emmpaul/laravel-spotify)[ GitHub Sponsors]()[ RSS](/packages/emmpaul-laravel-spotify/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (10)Versions (13)Used By (0)

Laravel Spotify Authentication &amp; API Wrapper
================================================

[](#laravel-spotify-authentication--api-wrapper)

A comprehensive Laravel package that provides Spotify OAuth authentication and a complete wrapper around the Spotify Web API.

Features
--------

[](#features)

- 🔐 **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

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require emmpaul/laravel-spotify
```

You can publish the config and migrations with:

```
php artisan vendor:publish --provider="emmpaul\LaravelSpotify\LaravelSpotifyServiceProvider"
```

Then run the migrations:

```
php artisan migrate
```

Environment Variables
---------------------

[](#environment-variables)

Add 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_login` and `scopes` to match your application needs.

Usage
-----

[](#usage)

### User Model Setup

[](#user-model-setup)

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...
}
```

### Authentication Routes

[](#authentication-routes)

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');
```

### Basic Authentication Flow

[](#basic-authentication-flow)

In your view or controller:

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

$spotifyAuthUrl = LaravelSpotify::getAuthUrl();
```

Or use the named route:

```
Login with Spotify
```

### User Methods

[](#user-methods)

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();
```

### Using the Spotify API

[](#using-the-spotify-api)

#### Via Facade

[](#via-facade)

```
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();
```

#### Via Service Class

[](#via-service-class)

```
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');
```

#### Using with Authenticated User

[](#using-with-authenticated-user)

```
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(),
    ]);
}
```

### Available API Methods

[](#available-api-methods)

#### Albums

[](#albums)

```
$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();
```

#### Artists

[](#artists)

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

#### Tracks

[](#tracks)

```
$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]);
```

#### Playlists

[](#playlists)

```
// 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);
```

#### User Data

[](#user-data)

```
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);
```

#### Player/Playback

[](#playerplayback)

```
$spotify->api()->getPlaybackState();
$spotify->api()->getCurrentlyPlayingTrack();
$spotify->api()->getAvailableDevices();
$spotify->api()->getTheUsersQueue();
```

#### Shows

[](#shows)

```
$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]);
```

#### Episodes

[](#episodes)

```
$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

[](#search)

```
// 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);
```

### Error Handling

[](#error-handling)

```
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());
}
```

### Time Ranges

[](#time-ranges)

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);
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Emmanuel Paul](https://github.com/emmpaul)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance88

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 58.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~52 days

Total

4

Last Release

88d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3be755e2aa7a81c22d62261db654966fe5a1b1129c41e9669fac2e7de4057a33?d=identicon)[emmpauldev](/maintainers/emmpauldev)

---

Top Contributors

[![emmpaul](https://avatars.githubusercontent.com/u/95937505?v=4)](https://github.com/emmpaul "emmpaul (17 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![emmpauldev](https://avatars.githubusercontent.com/u/118765640?v=4)](https://github.com/emmpauldev "emmpauldev (4 commits)")[![shahzeb1](https://avatars.githubusercontent.com/u/1383831?v=4)](https://github.com/shahzeb1 "shahzeb1 (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravellaravel-spotifyEmmanuel Paul

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/emmpaul-laravel-spotify/health.svg)

```
[![Health](https://phpackages.com/badges/emmpaul-laravel-spotify/health.svg)](https://phpackages.com/packages/emmpaul-laravel-spotify)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[jeffgreco13/filament-breezy

A custom package for Filament with login flow, profile and teams support.

1.0k1.7M41](/packages/jeffgreco13-filament-breezy)[spatie/laravel-login-link

Quickly login to your local environment

4381.2M1](/packages/spatie-laravel-login-link)[ryangjchandler/laravel-cloudflare-turnstile

A simple package to help integrate Cloudflare Turnstile.

438896.6k2](/packages/ryangjchandler-laravel-cloudflare-turnstile)[spatie/laravel-passkeys

Use passkeys in your Laravel app

444494.4k16](/packages/spatie-laravel-passkeys)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
