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

Laravel Dashboard Belgian Trains Tile Laravel Package

spatie/laravel-dashboard-belgian-trains-tile

Laravel Dashboard tile that shows Belgian train connections and their status. Install it in a Spatie Laravel Dashboard to display live updates for selected routes as a simple, glanceable tile.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:
    composer require spatie/laravel-dashboard-belgian-trains-tile
    
  2. Publish the configuration (if needed):
    php artisan vendor:publish --provider="Spatie\BelgianTrainsTile\BelgianTrainsTileServiceProvider"
    
  3. Register the tile in your Laravel Dashboard configuration (e.g., config/dashboard.php):
    'tiles' => [
        \Spatie\BelgianTrainsTile\BelgianTrainsTile::class,
    ],
    
  4. Add the tile to your dashboard via Livewire:
    use Spatie\BelgianTrainsTile\BelgianTrainsTile;
    
    public function mount()
    {
        $this->tiles[] = BelgianTrainsTile::class;
    }
    

First Use Case

Display real-time Belgian train connections for a specific station (e.g., Brussels Central) on your dashboard:

// In your Livewire component or dashboard config
BelgianTrainsTile::new()
    ->station('BRU') // Brussels Central
    ->departuresOnly() // Optional: Show only departures
    ->limit(5); // Show top 5 results

Implementation Patterns

Core Workflows

  1. Basic Integration

    • Use the tile as-is for a simple, pre-styled display of Belgian train schedules.
    • Example: Add to a dashboard for logistics teams tracking employee commutes.
  2. Customizing Station and Query Parameters

    • Dynamically set stations or departure/arrival filters based on user input:
      BelgianTrainsTile::new()
          ->station($request->input('station_code'))
          ->departuresOnly($showDepartures)
          ->limit($request->input('limit', 5));
      
  3. Extending with Additional Data

    • Override the tile’s view to include extra context (e.g., user-specific notes):
      // In a custom Livewire component
      public function render()
      {
          return view('livewire.custom-train-tile', [
              'trainData' => BelgianTrainsTile::new()->station('BRU')->getData(),
              'userNotes' => $this->getUserNotes(),
          ]);
      }
      
  4. Timezone Handling

    • Leverage the fixed timezone rendering (4.0.2) to ensure local time display:
      // Ensure app timezone is set (e.g., Europe/Brussels)
      config(['app.timezone' => 'Europe/Brussels']);
      
  5. Error Handling and Fallbacks

    • Gracefully handle API failures or empty results:
      try {
          $tile = BelgianTrainsTile::new()->station('BRU')->getData();
      } catch (\Exception $e) {
          $tile = ['error' => 'Train data unavailable. Retry later.'];
      }
      

Integration Tips

  • Caching: Cache API responses to reduce NMBS rate limits and improve performance:
    $cacheKey = 'belgian_trains_'.md5($station);
    $trainData = Cache::remember($cacheKey, now()->addMinutes(15), function () use ($station) {
        return BelgianTrainsTile::new()->station($station)->getData();
    });
    
  • Localization: Use Laravel’s localization features to support multiple languages:
    // In your Livewire component
    public function getTranslation()
    {
        return __('train_status.' . $this->trainData['status']);
    }
    
  • Testing: Mock the NMBS API to test edge cases (e.g., timezone changes, API failures):
    // In a PHPUnit test
    BelgianTrainsTile::shouldReceive('fetchData')
        ->once()
        ->andReturn(['status' => 'delayed']);
    

Gotchas and Tips

Pitfalls

  1. Timezone Misalignment

    • Issue: Train times may still render incorrectly if the app’s timezone is not set to Europe/Brussels or a compatible Belgian timezone.
    • Fix: Explicitly set the timezone in your .env:
      APP_TIMEZONE=Europe/Brussels
      
    • Debug: Verify timezone rendering by logging the output of now()->format('H:i') in your tile’s view.
  2. NMBS API Rate Limits

    • Issue: Frequent requests may hit NMBS’s rate limits, especially in high-traffic dashboards.
    • Fix: Implement caching (as shown above) and monitor API usage.
  3. Hardcoded Station Codes

    • Issue: The tile expects NMBS station codes (e.g., BRU for Brussels Central), which may not be intuitive for end users.
    • Fix: Create a mapping layer (e.g., database table or JSON config) to translate user-friendly names to codes:
      $stationCode = StationMapper::getCode($userInput);
      BelgianTrainsTile::new()->station($stationCode);
      
  4. Livewire Version Conflicts

    • Issue: The package supports Livewire 2 and 3, but mixing versions may cause runtime errors.
    • Fix: Ensure your laravel-dashboard and livewire packages are compatible:
      composer require laravel-dashboard:^4.0 livewire:^3.0
      
  5. Limited Customization

    • Issue: The tile’s UI is tightly coupled to Spatie’s dashboard styling, making it difficult to customize without forking.
    • Fix: Extend the tile’s view by publishing and overriding its templates:
      php artisan vendor:publish --tag=belgian-trains-tile-views
      
      Then modify resources/views/vendor/belgian-trains-tile/....

Debugging Tips

  1. API Response Inspection

    • Log the raw NMBS API response to debug issues:
      BelgianTrainsTile::new()->station('BRU')->getData();
      // Add a tap() method or use a debugger to inspect the response.
      
  2. Timezone Debugging

    • Force a specific timezone for testing:
      with(new DateTimeZone('Europe/Brussels'), function () {
          $tile = BelgianTrainsTile::new()->station('BRU');
          // Test rendering
      });
      
  3. Error Handling

    • Wrap tile usage in try-catch blocks to log errors:
      try {
          $tileData = BelgianTrainsTile::new()->station('BRU')->getData();
      } catch (\Exception $e) {
          Log::error('Belgian Trains Tile Error: ' . $e->getMessage());
          $tileData = ['error' => 'Failed to load train data.'];
      }
      

Extension Points

  1. Custom Data Sources

    • Override the fetchData method to use a different API or data source:
      BelgianTrainsTile::macro('customFetch', function () {
          return $this->fetchDataFromCustomSource();
      });
      
  2. Additional Metrics

    • Extend the tile to include derived metrics (e.g., average delay, frequency):
      BelgianTrainsTile::macro('withMetrics', function () {
          $data = $this->getData();
          $data['metrics'] = $this->calculateMetrics($data);
          return $data;
      });
      
  3. Multi-Station Support

    • Create a composite tile for multiple stations:
      BelgianTrainsTile::macro('multiStation', function (array $stations) {
          $tiles = [];
          foreach ($stations as $station) {
              $tiles[] = BelgianTrainsTile::new()->station($station)->getData();
          }
          return ['stations' => $tiles];
      });
      
  4. Real-Time Updates

    • Use Livewire’s polling to refresh train data periodically:
      public $refreshInterval = 60; // seconds
      
      public function updatedRefreshInterval()
      {
          $this->dispatch('refresh-tile');
      }
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony