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 Datatables Html Laravel Package

yajra/laravel-datatables-html

Laravel DataTables HTML plugin for building DataTables markup and initialization scripts in PHP. Integrates with yajra/laravel-datatables and supports Laravel 12+. Includes an HTML Builder, column definitions, and Vite-friendly module setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package alongside yajra/laravel-datatables:
    composer require yajra/laravel-datatables yajra/laravel-datatables-html
    
  2. Configure Vite (if using Laravel 11+): In AppServiceProvider@boot():
    Builder::useVite();
    
  3. First use case: Render a basic table in a Blade view:
    // routes/web.php
    Route::get('/users', [UserController::class, 'index']);
    
    // UserController.php
    public function index()
    {
        return DataTables::of(User::query())
            ->addColumn('action', 'users.action')
            ->make(true);
    }
    
    <!-- resources/views/users/index.blade.php -->
    {!! DataTables::table(['id', 'name', 'email', 'action'], 'users') !!}
    

Key Starting Points

  • Documentation: Laravel DataTables HTML Docs
  • Builder Methods: Focus on DataTables::of() + ->make(true) for server-side processing.
  • Vite Integration: Use Builder::useVite() to avoid CDN dependencies.

Implementation Patterns

Core Workflows

  1. Server-Side Processing with HTML Builder

    // Controller
    public function index()
    {
        $builder = DataTables::of(User::query())
            ->editColumn('name', '{{ ucfirst($name) }}')
            ->addColumn('status', function($row) {
                return $row->is_active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>';
            })
            ->addIndexColumn()
            ->make(true);
    
        return view('users.index', compact('builder'));
    }
    
    <!-- View -->
    {!! $builder->table(['id', 'name', 'email', 'status'], ['class' => 'table table-striped']) !!}
    {!! $builder->scripts() !!}
    
  2. Dynamic Column Visibility

    $builder = DataTables::of(User::query())
        ->addColumn('name', 'name')
        ->addColumn('email', 'email')
        ->addColumn('created_at', 'created_at')
        ->visibleIf('admin', ['email', 'created_at']); // Hide unless user is admin
    
  3. Vite + DataTables Integration

    // resources/js/app.js
    import 'datatables.net-dt/js/dataTables.dataTables';
    import 'datatables.net-responsive-dt/js/dataTables.responsive';
    
    // AppServiceProvider
    Builder::useVite();
    
  4. Livewire Integration

    public function index()
    {
        return DataTables::of(User::query())
            ->useLivewire()
            ->make(true);
    }
    
    {!! $builder->table(['id', 'name']) !!}
    @livewireScripts
    {!! $builder->scripts() !!}
    

Integration Tips

  • Reusable Table Definitions: Create a TableBuilder facade or service to encapsulate common configurations (e.g., AdminTable::users()).
  • Column Macros: Extend functionality with macros:
    DataTables::macro('statusColumn', function($row) {
        return $row->is_active ? 'Active' : 'Inactive';
    });
    
  • Editor Integration: For CRUD operations:
    $builder = DataTables::of(User::query())
        ->editColumn('name', 'name')
        ->addEditorColumn('name', 'name')
        ->make(true);
    

Gotchas and Tips

Pitfalls

  1. Vite Script Loading

    • Issue: Scripts fail to load if Builder::useVite() is not set or Vite is misconfigured.
    • Fix: Ensure datatables.net-dt and dependencies are imported in your Vite entry file (e.g., resources/js/app.js).
  2. Column Visibility Logic

    • Issue: visibleIf() may not work as expected if the condition is not properly bound to the view.
    • Fix: Pass the condition variable to the view:
      return view('users.index', [
          'builder' => $builder,
          'isAdmin' => auth()->user()->is_admin,
      ]);
      
      {!! $builder->visibleIf($isAdmin, ['email', 'created_at'])->table(...) !!}
      
  3. Livewire Conflicts

    • Issue: Livewire may interfere with DataTables initialization.
    • Fix: Use useLivewire() sparingly and ensure Livewire components are properly mounted before DataTables scripts run.
  4. CSRF Token Mismatch

    • Issue: Editor operations may fail with CSRF errors.
    • Fix: Ensure {{ csrf_field() }} is included in forms or use Laravel’s @csrf directive.

Debugging Tips

  • Check Generated HTML/JS: Use browser dev tools to inspect the rendered table and scripts. Look for missing assets or syntax errors.
  • Log Builder Output: Temporarily log the builder’s output to verify configurations:
    dd($builder->getJson());
    
  • Clear Vite Cache: If scripts fail post-Vite update:
    npm run dev
    php artisan optimize:clear
    

Extension Points

  1. Custom Templates Override default templates (e.g., table, scripts) by publishing assets:

    php artisan vendor:publish --tag=datatables-html
    

    Then modify resources/views/vendor/datatables/.

  2. Dynamic Column Rendering Use Blade components for complex columns:

    ->addColumn('avatar', function($row) {
        return view('components.avatar', ['user' => $row]);
    })
    
  3. Button Customization Extend buttons with custom logic:

    ->addButton('customExport', 'Export', 'export', 'export', fn($query) => [
        'action' => route('users.export'),
        'title' => 'CSV Export',
    ])
    
  4. Performance

    • Lazy Loading: Use ->useLivewire() or AJAX for large datasets.
    • Column Filtering: Limit columns in queries to reduce payload:
      ->select(['id', 'name', 'email']) // Only fetch needed columns
      
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