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 Widgets Laravel Package

arrilot/laravel-widgets

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require arrilot/laravel-widgets
    php artisan vendor:publish --provider="Arrilot\Widgets\WidgetsServiceProvider" --tag="widgets-config"
    

    Publish the config file to customize widget behavior (e.g., caching, async settings).

  2. Generate a Widget:

    php artisan make:widget RecentNews
    

    This creates:

    • A widget class (app/Widgets/RecentNews.php) extending AbstractWidget.
    • A view stub (resources/views/widgets/recent_news.blade.php).
  3. First Use Case: Register the widget in a controller or view composer:

    use App\Widgets\RecentNews;
    use Arrilot\Widgets\Facades\Widgets;
    
    // In a controller:
    public function dashboard()
    {
        Widgets::add('recent_news', RecentNews::class, ['config' => ['limit' => 5]]);
        return view('dashboard');
    }
    

    Or directly in a view:

    @widget('recent_news', ['config' => ['limit' => 5]])
    

Implementation Patterns

Core Workflows

  1. Widget Registration:

    • Dynamic Registration: Use Widgets::add() in controllers, middleware, or service providers.
      Widgets::add('analytics', AnalyticsWidget::class, ['user_id' => auth()->id()]);
      
    • Global Registration: Register widgets in AppServiceProvider@boot() for app-wide reuse.
      public function boot()
      {
          Widgets::register('sidebar', SidebarWidget::class);
      }
      
  2. Asynchronous Widgets: Enable async loading in config/widgets.php:

    'async' => true,
    

    Use @widget directive with async:

    @widget('recent_news', ['async' => true])
    
    • Partial Async: Load only specific widgets asynchronously for performance.
  3. Reloadable Widgets: Use Widgets::reload() to refresh widget data without reloading the entire page:

    // Via AJAX
    $.get('/widget/reload/recent_news', function(data) {
        $('#widget-recent_news').html(data);
    });
    

    Ensure your widget class implements shouldReload():

    public function shouldReload()
    {
        return request()->ajax();
    }
    
  4. Caching: Leverage built-in caching (Redis, file, etc.) via config:

    'cache' => [
        'driver' => 'file',
        'minutes' => 60,
    ],
    
    • Cache Invalidation: Manually clear widget cache:
      Widgets::clearCache('recent_news');
      
  5. Data Passing:

    • Config Arrays: Pass data via the config parameter:
      Widgets::add('user_stats', UserStatsWidget::class, [
          'user_id' => 1,
          'metrics' => ['active', 'inactive']
      ]);
      
    • View Data: Extend the widget’s run() method to merge additional data:
      public function run()
      {
          return view('widgets.user_stats', [
              'user' => User::find($this->config['user_id']),
              'metrics' => $this->config['metrics'],
          ]);
      }
      
  6. Conditional Rendering: Use shouldRender() to control widget visibility:

    public function shouldRender()
    {
        return auth()->check() && auth()->user()->isAdmin();
    }
    

Integration Tips

  • Middleware: Register widgets in middleware to apply them globally to routes:
    public function handle($request, Closure $next)
    {
        Widgets::add('notifications', NotificationWidget::class);
        return $next($request);
    }
    
  • Livewire/Alpine: Combine with frontend frameworks for dynamic updates:
    @widget('live_chart', ['async' => true, 'data' => $chartData])
    <script>
        document.addEventListener('livewire:init', () => {
            Livewire.on('chartUpdated', data => {
                Widgets.reload('live_chart', { data });
            });
        });
    </script>
    
  • Testing: Mock widgets in tests:
    $widget = Mockery::mock(RecentNews::class);
    $widget->shouldReceive('run')->andReturn(view('widgets.mock_recent_news'));
    Widgets::add('recent_news', $widget);
    

Gotchas and Tips

Pitfalls

  1. Caching Conflicts:

    • Issue: Widgets may not update if cached aggressively.
    • Fix: Use Widgets::clearCache() or adjust cache.minutes in config.
    • Debug: Check storage/framework/cache/widgets/ for stale files.
  2. Async Loading Quirks:

    • Issue: Async widgets may fail silently if JavaScript is disabled.
    • Fix: Provide a fallback in Blade:
      @widget('recent_news', ['async' => true])
      @include('widgets.fallback_recent_news')
      
    • Debug: Verify async routes exist in routes/web.php (auto-generated by the package).
  3. Route Collisions:

    • Issue: Async widgets create routes like /widget/reload/{name}. Conflicts may arise with existing routes.
    • Fix: Explicitly define widget routes in routes/web.php:
      Route::widget('recent_news');
      
  4. View Path Assumptions:

    • Issue: The package assumes views are in resources/views/widgets/{name}.blade.php.
    • Fix: Override the view path in the widget class:
      protected $view = 'custom.path.widget';
      
  5. Configuration Overrides:

    • Issue: Global config in config/widgets.php may be overridden by per-widget settings.
    • Fix: Use Widgets::config() to set defaults:
      Widgets::config(['cache.minutes' => 30]);
      

Debugging

  1. Widget Not Rendering:

    • Check if the widget is registered:
      dd(Widgets::get('recent_news'));
      
    • Verify shouldRender() returns true.
    • Inspect the view path and ensure it exists.
  2. Async Widgets Failing:

    • Check browser console for 404 errors on /widget/reload/{name}.
    • Ensure shouldReload() logic is correct (e.g., request()->ajax()).
  3. Performance Issues:

    • Profile widget execution time:
      public function run()
      {
          $start = microtime(true);
          $data = $this->fetchData();
          $time = microtime(true) - $start;
          Log::debug("Widget executed in {$time}s");
          return view(...);
      }
      
    • Disable caching temporarily to isolate slow queries.

Extension Points

  1. Custom Directives: Extend Blade directives by publishing the package’s views and modifying app/Providers/BladeServiceProvider.php:

    public function boot()
    {
        Blade::directive('widget', function ($expression) {
            return "<?php echo Arrilot\Widgets\Facades\Widgets::render($expression); ?>";
        });
    }
    
  2. Widget Events: Listen to widget events (e.g., widget.rendering, widget.rendered):

    event(new WidgetRendering($widget));
    

    Register listeners in EventServiceProvider.

  3. Dynamic Widget Classes: Load widget classes dynamically based on user roles or other conditions:

    $widgetClass = auth()->user()->isAdmin() ? AdminDashboardWidget::class : UserDashboardWidget::class;
    Widgets::add('dashboard', $widgetClass);
    
  4. API Widgets: Return JSON responses for API consumers:

    public function run()
    {
        if (request()->wantsJson()) {
            return response()->json(['data' => $this->fetchData()]);
        }
        return view(...);
    }
    
  5. Widget Dependencies: Define dependencies between widgets (e.g., analytics requires user_data):

    public function dependencies()
    {
        return ['user_data'];
    }
    

    Ensure dependencies are registered first:

    Widgets::add('user_data', UserDataWidget::class);
    Widgets::add('analytics', AnalyticsWidget::class);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware