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 Time Weather Tile Laravel Package

spatie/laravel-dashboard-time-weather-tile

Laravel Dashboard tile by Spatie that shows current time plus local weather. Plug it into your dashboard to keep an eye on conditions at a glance, with configuration handled via the Laravel Dashboard ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-dashboard-time-weather-tile
    

    Ensure laravel-dashboard is installed (this package is a tile for it).

  2. Register the Tile: Add the tile to your dashboard configuration in config/dashboard.php:

    'tiles' => [
        \Spatie\Dashboard\Tiles\TimeWeatherTile::class,
    ],
    
  3. First Use Case:

    • Publish the config (if needed) with:
      php artisan vendor:publish --provider="Spatie\Dashboard\DashboardServiceProvider"
      
    • Configure your API keys for weather services (e.g., OpenWeatherMap) in .env:
      DASHBOARD_WEATHER_API_KEY=your_api_key_here
      DASHBOARD_WEATHER_LOCATION=your_city
      
    • Visit your dashboard (/dashboard) to see the tile displaying local time and weather.

Implementation Patterns

Core Workflows

  1. Dynamic Tile Integration:

    • Use the tile alongside other laravel-dashboard tiles in a single dashboard view. Example:
      // In a controller or blade view
      use Spatie\Dashboard\Tiles\TimeWeatherTile;
      
      $tiles = [
          new TimeWeatherTile(),
          new OtherTile(),
      ];
      return view('dashboard', compact('tiles'));
      
  2. Customizing Appearance:

    • Override default styling by publishing the views:
      php artisan vendor:publish --tag=dashboard-views
      
    • Modify resources/views/vendor/dashboard/tiles/time-weather.blade.php to adjust layout, colors, or icons.
  3. Conditional Rendering:

    • Disable the tile based on user roles or settings:
      if (auth()->user()->canSeeWeather()) {
          $tiles[] = new TimeWeatherTile();
      }
      
  4. Localization:

    • Translate time/weather labels using Laravel’s localization:
      // In config/dashboard.php
      'tiles' => [
          (new TimeWeatherTile())->setTimeLabel(__('dashboard.time')),
      ],
      
  5. API Key Management:

    • Store sensitive keys in .env and use Laravel’s config() helper:
      $tile = new TimeWeatherTile(config('dashboard.weather_api_key'));
      

Integration Tips

  • Weather Service Flexibility: Extend the tile to support multiple weather APIs (e.g., AccuWeather) by implementing a WeatherService contract and binding it in the DashboardServiceProvider.

  • Caching: Cache weather data to reduce API calls (e.g., using Laravel’s cache):

    $weather = Cache::remember('weather_data', now()->addHours(1), function () {
        return $this->weatherService->getWeather();
    });
    
  • Testing: Mock the weather service in tests:

    $this->mock(WeatherService::class, function ($mock) {
        $mock->shouldReceive('getWeather')->andReturn(['temp' => 20, 'condition' => 'sunny']);
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Leaks:

    • Risk: Hardcoding API keys in blade views or controllers.
    • Fix: Always use .env and Laravel’s config system. Avoid logging or exposing keys in client-side code.
  2. Rate Limiting:

    • Issue: Free weather APIs (e.g., OpenWeatherMap) have call limits. Excessive dashboard refreshes may hit limits.
    • Solution: Implement caching (as above) or use a paid API tier.
  3. Time Zone Mismatches:

    • Problem: The tile defaults to the server’s time zone. Users in different regions may see incorrect times.
    • Fix: Pass a user-specific time zone:
      $tile = new TimeWeatherTile();
      $tile->setTimeZone(auth()->user()->timezone);
      
  4. Missing Dependencies:

    • Error: Class 'Spatie\Dashboard\Tiles\TimeWeatherTile' not found.
    • Cause: laravel-dashboard is not installed or autoloaded.
    • Fix: Run composer dump-autoload and ensure laravel-dashboard is in composer.json.
  5. Weather Data Errors:

    • Symptom: Tile shows "Weather data unavailable."
    • Debugging:
      • Verify .env keys are correct.
      • Check API response format matches the tile’s expectations (e.g., OpenWeatherMap’s weather vs. main.temp).
      • Log the raw API response for debugging:
        \Log::debug('Weather API response:', $this->weatherService->getWeather());
        

Debugging Tips

  1. Log API Responses: Add temporary logging in the tile’s render() method to inspect data:

    \Log::debug('Weather data:', $weatherData);
    
  2. Validate Config: Ensure config/dashboard.php includes:

    'weather' => [
        'api_key' => env('DASHBOARD_WEATHER_API_KEY'),
        'location' => env('DASHBOARD_WEATHER_LOCATION', 'New York'),
        'unit' => env('DASHBOARD_WEATHER_UNIT', 'metric'), // or 'imperial'
    ],
    
  3. Unit Testing: Test edge cases like:

    • Invalid API keys (should gracefully handle errors).
    • Missing weather data (fallback UI).
    • Time zone changes.

Extension Points

  1. Custom Weather Icons: Override the default icons by extending the tile:

    class CustomTimeWeatherTile extends TimeWeatherTile {
        public function getWeatherIcon($condition) {
            return match ($condition) {
                'rain' => '☔', // Custom icon
                default => parent::getWeatherIcon($condition),
            };
        }
    }
    
  2. Additional Data: Extend the tile to show humidity, wind speed, or forecasts:

    // In the tile's render method
    $forecast = $this->weatherService->getForecast();
    return view('dashboard::tiles.time-weather', [
        'forecast' => $forecast,
    ]);
    
  3. Dark Mode Support: Dynamically adjust tile styling based on user preferences:

    $tile->setDarkMode(auth()->user()->prefers_dark_mode);
    
  4. Geolocation: Auto-detect user location (with permission) and update the weather tile:

    // Frontend JavaScript
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            axios.post('/update-weather-location', {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
            });
        });
    }
    
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