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

Dashboard Bundle Laravel Package

2lenet/dashboard-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require 2lenet/dashboard-bundle in your Laravel project (note: this bundle is Symfony-based, but can be adapted for Laravel via Symfony Bridge or Laravel Mix).

  2. Configuration Add the bundle to config/services.yaml (or Laravel’s equivalent service provider binding):

    App\Widgets\:
        resource: '../src/Widgets'
        tags: ['tkuska_dashboard.widget']
    

    Register routes in routes.yaml (or Laravel’s routes/web.php):

    require __DIR__.'/../vendor/tkuska/dashboard-bundle/Resources/config/routes.yaml';
    
  3. Database Setup Create and run a migration for the widget table:

    php artisan make:migration create_widgets_table
    

    Update the migration file to match the bundle’s expected schema (e.g., id, user_id, type, config, order). Run:

    php artisan migrate
    
  4. First Widget Create a widget class in src/Widgets/ extending AbstractWidget:

    namespace App\Widgets;
    
    use Tkuska\DashboardBundle\Widgets\AbstractWidget;
    
    class ExampleWidget extends AbstractWidget {
        public function getName() { return 'Example Widget'; }
        public function getJsonSchema() { return []; } // Empty schema for now
        public function support() { return true; }
    }
    
  5. Test the Dashboard Visit /dashboard (or the route defined in the bundle) to see your widget in action.


Implementation Patterns

Widget Development Workflow

  1. Extending AbstractWidget Override core methods to customize behavior:

    • getName(): Human-readable widget name (e.g., "User Stats").
    • getJsonSchema(): Define configurable fields using JSON Schema. Example:
      public function getJsonSchema() {
          return [
              'type' => 'object',
              'properties' => [
                  'title' => ['type' => 'string', 'default' => 'Default Title'],
                  'limit' => ['type' => 'integer', 'default' => 10],
              ],
          ];
      }
      
    • transformResponse(): Modify the widget’s output (e.g., wrap in a partial view or API response).
  2. Configuration Management

    • Use getConfigForm() to customize the admin UI for widget settings (rarely needed; default form works for JSON Schema).
    • Store configurations in the widget.config column (serialized JSON).
  3. Dynamic Loading

    • Set supportsAjax() to true for lazy-loaded widgets (e.g., heavy or API-dependent widgets).
    • Example:
      public function supportsAjax() { return true; }
      
  4. Integration with Laravel

    • Service Injection: Bind Symfony services (e.g., Twig_Environment) to Laravel’s container via AppServiceProvider:
      public function register() {
          $this->app->singleton('twig', function () {
              return \Twig\Environment::newLoader(new \Twig\Loader\FilesystemLoader(__DIR__.'/../resources/views'));
          });
      }
      
    • Routing: Override bundle routes in routes/web.php:
      Route::prefix('dashboard')->group(function () {
          require __DIR__.'/../vendor/tkuska/dashboard-bundle/Resources/config/routes.yaml';
      });
      
  5. Widget Rendering

    • Override render() (if needed) to customize output:
      public function render() {
          return $this->twig->render('widgets/example.html.twig', [
              'config' => $this->config,
          ]);
      }
      
    • Use Twig templates in resources/views/widgets/.
  6. User-Specific Dashboards

    • Attach widgets to users via user_id in the widgets table.
    • Filter widgets in queries:
      $widgets = Widget::where('user_id', auth()->id())->orderBy('order')->get();
      

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch

    • The bundle expects a widgets table with columns like id, user_id, type, config (JSON), and order. Custom migrations may break functionality.
    • Fix: Compare with the bundle’s default schema or use doctrine:migrations:diff to generate a compatible migration.
  2. Twig Environment Issues

    • The bundle assumes a Symfony Twig environment. In Laravel, ensure Twig is properly bound (see Implementation Patterns).
    • Debug: Check for Twig_Environment binding errors in logs.
  3. JSON Schema Validation

    • Invalid schemas in getJsonSchema() may cause silent failures or malformed UI forms.
    • Tip: Validate schemas using JSON Schema Validator before implementation.
  4. Route Conflicts

    • The bundle’s routes (e.g., /dashboard) may clash with Laravel’s default routes.
    • Fix: Override routes in routes/web.php or use route namespaces:
      # In routes.yaml
      dashboard_widgets:
          path: /admin/dashboard
      
  5. Widget Ordering

    • Widgets are ordered by the order column. Manual reordering requires updating this column (e.g., via a drag-and-drop UI or admin panel).
  6. Caching Headaches

    • Widget configurations are stored as JSON. Deeply nested or large configs may cause serialization issues.
    • Tip: Limit config size or use a separate table for complex data.

Debugging Tips

  1. Log Widget Configs Dump configs in getJsonSchema() or render() to verify data:

    \Log::debug('Widget config:', $this->config);
    
  2. Check Bundle Events The bundle may dispatch events (e.g., dashboard.widget.render). Listen for them in Laravel’s event system:

    Event::listen('dashboard.widget.render', function ($widget) {
        \Log::info('Rendering widget:', $widget->getName());
    });
    
  3. Disable Widgets Safely Set support() { return false; } to hide widgets without deleting them.

Extension Points

  1. Custom Widget Types Extend AbstractWidget to create reusable widget templates (e.g., ChartWidget, TableWidget).

  2. Admin Panel Integration Add a /dashboard/admin route to manage widgets (user assignment, reordering, deletion). Example:

    Route::get('/dashboard/admin', [DashboardController::class, 'admin'])->name('dashboard.admin');
    
  3. Widget Permissions Add middleware to restrict widget access:

    public function render() {
        if (!auth()->user()->can('view-dashboard')) {
            abort(403);
        }
        return parent::render();
    }
    
  4. Internationalization Use Twig’s trans filter in widget templates for multi-language support:

    {{ 'widget.title'|trans({ 'name': config.title }) }}
    
  5. Testing Widgets Mock AbstractWidget in PHPUnit tests:

    $widget = $this->createMock(AbstractWidget::class);
    $widget->method('getName')->willReturn('Test Widget');
    $widget->method('render')->willReturn('Mocked HTML');
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor