Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Last Fm Now Playing Laravel Package

spatie/last-fm-now-playing

Fetch the currently playing track for any Last.fm user. Provide your API key and username to retrieve artist, album, track name, artwork, and track URL, or false if nothing is playing. Throws BadResponse on errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/last-fm-now-playing
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Spatie\LastFmNowPlaying\LastFmNowPlayingServiceProvider"
    
  2. Configuration:

    • Set your Last.fm API key in .env:
      LASTFM_API_KEY=your_api_key_here
      
    • Configure the user whose now-playing status you want to fetch in config/last-fm-now-playing.php:
      'username' => 'your_lastfm_username',
      
  3. First Use Case: Fetch the currently playing track in a controller or service:

    use Spatie\LastFmNowPlaying\Facades\LastFmNowPlaying;
    
    $nowPlaying = LastFmNowPlaying::getNowPlaying();
    dd($nowPlaying); // Returns an array with track details (e.g., title, artist, album, etc.)
    

Implementation Patterns

Core Workflows

  1. Fetching Now-Playing Data:

    • Use the facade or service directly:
      $nowPlaying = LastFmNowPlaying::getNowPlaying();
      
    • Handle cases where no track is playing (returns null or an empty array).
  2. Integration with User Profiles:

    • Display the now-playing status on a user profile page:
      $user = User::find($id);
      $nowPlaying = LastFmNowPlaying::getNowPlayingForUser($user->lastfm_username);
      return view('profile', compact('user', 'nowPlaying'));
      
  3. Caching for Performance:

    • Cache the result to avoid repeated API calls (e.g., every 5 minutes):
      $nowPlaying = Cache::remember("lastfm_{$user->lastfm_username}_now_playing", now()->addMinutes(5), function () use ($user) {
          return LastFmNowPlaying::getNowPlayingForUser($user->lastfm_username);
      });
      
  4. Real-Time Updates:

    • Use Laravel Echo/Pusher to push updates when the now-playing status changes (requires polling or Last.fm webhooks if available).
  5. Error Handling:

    • Wrap API calls in a try-catch block to handle API failures gracefully:
      try {
          $nowPlaying = LastFmNowPlaying::getNowPlaying();
      } catch (\Exception $e) {
          Log::error("Last.fm API error: " . $e->getMessage());
          $nowPlaying = null;
      }
      

Advanced Patterns

  1. Dynamic User Handling:

    • Pass a username dynamically to fetch data for any user:
      $nowPlaying = LastFmNowPlaying::getNowPlayingForUser('dynamic_username');
      
  2. Combining with Other APIs:

    • Use the track data to fetch additional info (e.g., Spotify, YouTube) via other APIs.
  3. Broadcasting Updates:

    • Broadcast the now-playing status to connected clients (e.g., using Laravel Echo):
      broadcast(new NowPlayingUpdated($nowPlaying))->toOthers();
      
  4. Testing:

    • Mock the LastFmNowPlaying service in tests:
      $this->partialMock(Spatie\LastFmNowPlaying\LastFmNowPlaying::class, function ($mock) {
          $mock->shouldReceive('getNowPlaying')->andReturn(['track' => 'Test Track']);
      });
      

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

    • Last.fm has rate limits (typically 300 calls/hour for non-commercial use). Cache aggressively to avoid hitting limits.
    • Monitor API usage via the Last.fm API docs.
  2. No Track Playing:

    • The API may return null or an empty response if the user isn’t listening to anything. Always check for this:
      if (empty($nowPlaying)) {
          return "User is not listening to anything right now.";
      }
      
  3. API Key Restrictions:

    • Ensure your API key is not shared publicly (e.g., in client-side code). Use it only server-side.
  4. Deprecated Methods:

    • The package is last updated in 2020. Verify compatibility with Last.fm’s current API if using newer features.
  5. Time Zone Issues:

    • Last.fm’s "now playing" data is based on the user’s local time. If you need UTC, adjust the response manually.

Debugging Tips

  1. Enable Debugging:

    • Set LASTFM_DEBUG in .env to true to log API requests/responses:
      LASTFM_DEBUG=true
      
  2. Check API Response:

    • Log the raw response to debug issues:
      $response = LastFmNowPlaying::getNowPlaying();
      Log::debug('Last.fm API Response:', $response);
      
  3. Validate API Key:

    • Test your API key using the Last.fm API console to ensure it’s valid and has the required permissions.

Extension Points

  1. Customize Response:

    • Extend the Spatie\LastFmNowPlaying\LastFmNowPlaying class to modify the response format:
      class CustomLastFmNowPlaying extends \Spatie\LastFmNowPlaying\LastFmNowPlaying {
          public function getNowPlaying() {
              $data = parent::getNowPlaying();
              return $this->formatData($data);
          }
      
          protected function formatData($data) {
              // Custom formatting logic
              return $data;
          }
      }
      
  2. Add Retry Logic:

    • Implement retry logic for failed API calls using Laravel’s retry helper or a package like spatie/retries.
  3. Support Multiple Users:

    • Store multiple usernames in the config and fetch data for all:
      'usernames' => [
          'user1',
          'user2',
      ],
      
      Then loop through them in your code.
  4. Webhook Integration:

    • If Last.fm offers webhooks (or you use a proxy service), integrate them to push real-time updates instead of polling.
  5. Fallback Data:

    • Provide fallback data (e.g., recent tracks) if the now-playing API fails:
      $nowPlaying = LastFmNowPlaying::getNowPlaying();
      if (empty($nowPlaying)) {
          $nowPlaying = LastFmNowPlaying::getRecentTracks()->first();
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport