Download the PHP package bjthecod3r/laravel-spotify-api-wrapper without Composer
On this page you can find all versions of the php package bjthecod3r/laravel-spotify-api-wrapper. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download bjthecod3r/laravel-spotify-api-wrapper
More information about bjthecod3r/laravel-spotify-api-wrapper
Files in bjthecod3r/laravel-spotify-api-wrapper
Package laravel-spotify-api-wrapper
Short Description A Laravel wrapper for the Spotify Web API.
License MIT
Informations about the package laravel-spotify-api-wrapper
Laravel Spotify API Wrapper
A Laravel wrapper for the Spotify Web API. Search across tracks, albums, artists, playlists, shows, episodes, and audiobooks with a fluent facade and fully-typed responses.
Highlights
- Fluent search for every Spotify item type, with Spotify's full filter syntax (
artist:,year:,tag:new,isrc:, …) supported out of the box. - Typed responses. No more reaching into nested arrays — every response is hydrated into PHP objects with public typed properties (
$track->album->name,$album->releaseDateis aCarboninstance, etc.). - Pagination built in.
Paginatedexposesitems,total,limit,offset,next, andpreviousso you can page or drive a "Load more" button without parsing URLs. - Auth handled for you. Client-credentials tokens are fetched, cached for the duration Spotify reports, and transparently refreshed on a 401.
- Typed exceptions mapped from Spotify's status codes — catch
RateLimitExceptionto readretryAfter,AuthenticationExceptionfor credential issues, etc. - Drop-in JSON. Resources implement
Arrayable+JsonSerializable, soreturn $results;from a controller serializes correctly.
Requirements
- PHP
^8.2 - Laravel
^11.0,^12.0, or^13.0
Installation
Publish the config:
Add your Spotify app credentials to .env:
Search
Single-type search
The most common case — search one type, get a typed Paginated back:
Get a playlist
Search playlists hydrate as SimplifiedPlaylist summaries. Direct playlist lookups hydrate as
Playlist so followers and paginated tracks.items are only present on the
endpoint that returns them.
Get a single resource by ID
Direct lookups exist for every searchable resource, plus user profiles. They all
return a fully-typed resource (the same classes the search endpoints hydrate),
and accept ->market() where Spotify supports it.
Multi-type search
When you want several item types in one request:
Type strings work too if you'd rather skip the enum import:
Field filters
Spotify supports inline filters in the query string. Just pass them through:
Pagination
Typed resources
Every search response hydrates into objects under BjTheCod3r\Spotify\Resources\:
| Resource | Notable fields |
|---|---|
Track |
name, durationMs, explicit, popularity, previewUrl, album, artists |
Album |
name, albumType, totalTracks, releaseDate (Carbon), images, artists |
Artist |
name, genres, popularity, images, followers (Followers — href, total) |
SimplifiedPlaylist |
name, description, public, owner (User), tracks (TracksLink — href, total), items (PlaylistItemsLink), images |
Playlist |
name, description, public, followers, owner (User), tracks (TracksLink — href, total, items), images |
Show |
name, description, publisher, totalEpisodes, images |
Episode |
name, description, durationMs, releaseDate (Carbon), audioPreviewUrl |
Audiobook |
name, description, authors (Author[]), narrators (Narrator[]), publisher, totalChapters |
Image |
url, height, width |
Paginated<T> |
items, total, limit, offset, next, previous, href |
Date fields are real Illuminate\Support\Carbon instances. Spotify's date precision (year, month, day) is preserved on round-trip via releaseDatePrecision.
List fields (items, artists, images, genres, languages, authors, narrators, …) are Illuminate\Support\Collection instances, so you get the full Laravel Collection API:
Resources implement Arrayable + JsonSerializable, so this works:
Laravel will serialize the Paginated<Track> to JSON automatically.
Error handling
| Status | Exception |
|---|---|
| 400 / 422 | BjTheCod3r\Spotify\Exceptions\ValidationException |
| 401 | BjTheCod3r\Spotify\Exceptions\AuthenticationException (after a transparent token refresh + retry) |
| 429 | BjTheCod3r\Spotify\Exceptions\RateLimitException — exposes retryAfter in seconds |
| Other 4xx/5xx | BjTheCod3r\Spotify\Exceptions\ApiException |
All inherit from BjTheCod3r\Spotify\Exceptions\SpotifyException, so you can catch broadly:
Authentication
The package uses Spotify's Client Credentials grant — no user login required, suitable for any endpoint that doesn't need user context (Search, Browse, Albums, Artists, Tracks). Tokens are cached using Laravel's cache for the duration Spotify reports in expires_in, minus a small safety buffer, so you only hit the auth endpoint when a token actually needs refreshing.
User authentication
For endpoints that act on a listener's account — their playlists, library, top items, listening history — connect their Spotify account via the Authorization Code + PKCE flow.
About playback. The Spotify Web API does not return playable audio URLs even for authenticated users. Full playback is gated to Spotify's Web Playback SDK (browser, Premium) and the mobile SDKs. The user-auth surface here is for reading user data and (in a future release) controlling an active device, not for direct streaming.
Setup
Publish the migration that stores per-user tokens, then run it:
Tokens are encrypted at rest using Laravel's app key.
Set the OAuth redirect URI on your .env (and register the same value on the Spotify dashboard for your app):
The package registers three opt-in routes under the spotify prefix (configurable):
| Method | URI | Name |
|---|---|---|
| GET | /spotify/connect |
spotify.connect |
| GET | /spotify/callback |
spotify.callback |
| POST | /spotify/disconnect |
spotify.disconnect |
Set spotify.oauth.routes.enabled to false (or env SPOTIFY_OAUTH_ROUTES_ENABLED=false) to disable them and wire your own controllers using the Spotify::redirect() / Spotify::handleCallback() helpers.
Connecting a user
Have the authenticated user hit the connect route — by default it requires the web + auth middleware:
Pass extra scopes via ?scopes=playlist-modify-public,user-modify-playback-state to merge with the configured defaults.
After consent, Spotify redirects to /spotify/callback. The controller exchanges the code, captures the listener's Spotify user id, persists encrypted tokens, dispatches SpotifyConnected, and redirects to oauth.after_connect.
If anything fails (state mismatch, user denied consent on Spotify, exchange error, …), the callback still redirects to oauth.after_connect but flashes a spotify.oauth.error payload onto the session so the destination can render error UX:
The reason is one of state_mismatch, user_denied, authorize_error, or exchange_failed; description carries the underlying Spotify error code or exception message.
Reading user data
All me() endpoints that return collections come back as the same Paginated resource the rest of the package uses. The me/tracks, me/albums, me/shows, me/episodes, and me/player/recently-played envelopes are unwrapped — the items collection contains the inner Track / Album / etc. directly. The added_at / played_at timestamps from those envelopes are not exposed in v0.3.
Token refresh & 401 handling
Access tokens are refreshed transparently when stale. A 401 from any API call forces an out-of-band refresh and retries the original request once, so a token revoked between issuance and use is recovered automatically.
If Spotify rejects the refresh token (invalid_grant) — typically because the user revoked access from their Spotify settings — the stored row is deleted and SpotifyDisconnected is fired with reason = invalid_grant, so your app can prompt the user to reconnect.
Concurrent refreshes are serialised per-user via Cache::lock, so a fan-out of queue workers doesn't double-spend a rotating refresh token.
Events
Listen for any of these to integrate with your app:
| Event | When |
|---|---|
SpotifyConnected |
After a successful callback exchange. |
SpotifyTokenRefreshed |
After any successful refresh-token grant. |
SpotifyDisconnected |
On explicit disconnect() or invalid_grant from refresh. |
SpotifyConnectFailed |
State mismatch, user denied consent, authorize error, exchange failure. |
Disconnecting
Or POST to route('spotify.disconnect') from a form. The default route stack includes web middleware, so the form must carry a CSRF token:
Custom token storage
The default Eloquent-backed repository covers most apps. To swap implementations (Redis, encrypted file, another DB connection), implement BjTheCod3r\Spotify\Contracts\UserTokenRepository and point at it:
Testing
The package ships with Pest + Orchestra Testbench:
In your own application's tests, fake the HTTP layer with Laravel's standard helpers:
Roadmap
- [x] Search
- [x] Albums, Artists, Tracks (Get-by-ID)
- [x] Episodes, Shows, Audiobooks (Get-by-ID)
- [x] Playlists (Get-by-ID, read-only)
- [x] Users — Authorization Code + PKCE,
me/*reads - [ ] Tracks (audio features / analysis)
- [ ] Browse (categories, new releases, featured playlists)
- [ ] Markets, Genres
- [ ] Player — playback control on the user's active device
- [ ] Playlist mutations (create / reorder / add-remove items)
License
MIT.
All versions of laravel-spotify-api-wrapper with dependencies
illuminate/contracts Version ^11.0|^12.0|^13.0
illuminate/http Version ^11.0|^12.0|^13.0
illuminate/support Version ^11.0|^12.0|^13.0