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

Tailwind Datatables Laravel Package

squipix/tailwind-datatables

View on GitHub
Deep Wiki
Context7
## Getting Started
Install the package via Composer:
```bash
composer require squipix/tailwind-datatables

Publish the configuration file (if needed) and assets:

php artisan vendor:publish --provider="Squipix\TailwindDataTables\TailwindDataTablesServiceProvider" --tag="config"
php artisan vendor:publish --provider="Squipix\TailwindDataTables\TailwindDataTablesServiceProvider" --tag="assets"

Register the service provider in config/app.php under providers if not auto-discovered.

First Use Case: Generate a basic Tailwind-styled DataTable for an Eloquent model:

use Squipix\TailwindDataTables\Facades\TailwindDataTables;

$table = TailwindDataTables::of(App\Models\User::query())
    ->addColumn('name', 'Name')
    ->addColumn('email', 'Email')
    ->addColumn('created_at', 'Created At')
    ->addIndexColumn()
    ->make(true);

Render the table in a Blade view:

{{ $table->table() }}

Implementation Patterns

1. Query Builder Integration

Leverage Laravel's query builder for dynamic filtering, sorting, and pagination:

$table = TailwindDataTables::of(App\Models\User::query())
    ->filter(function ($query) {
        $query->where('active', true);
    })
    ->sortable(['name', 'email', 'created_at'])
    ->paginate(10);

2. Column Customization

Define columns with custom rendering (e.g., buttons, badges, or computed values):

$table->addColumn('status', 'Status', function ($row) {
    return '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-' .
           ($row->active ? 'green' : 'red') .
           '-100 text-' .
           ($row->active ? 'green' : 'red') .
           '-800">'.($row->active ? 'Active' : 'Inactive').'</span>';
})->escape(false);

3. Actions & Buttons

Add action buttons (e.g., edit, delete) with Tailwind styling:

$table->addAction('actions', 'Actions', function ($row) {
    return '<div class="flex space-x-2">
        <a href="/users/' . $row->id . '/edit" class="text-blue-600 hover:text-blue-900">Edit</a>
        <form action="/users/' . $row->id . '" method="POST" class="inline">
            @csrf @method("DELETE")
            <button type="submit" class="text-red-600 hover:text-red-900">Delete</button>
        </form>
    </div>';
})->escape(false);

4. Bulk Actions

Implement bulk actions with checkboxes:

$table->addCheckboxColumn('select')
    ->bulkAction(function ($rows) {
        return '<button class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
            Delete Selected
        </button>';
    }, 'bulk_action')
    ->bulkDelete(function ($rows) {
        foreach ($rows as $row) {
            $row->delete();
        }
        return redirect()->back()->with('success', 'Items deleted!');
    });

5. Server-Side Processing

For large datasets, use server-side processing:

$table = TailwindDataTables::of(App\Models\User::query())
    ->serverSide()
    ->make(true);

6. Export Functionality

Add export buttons (CSV, Excel, PDF):

$table->exportButtons([
    'csv', 'excel', 'pdf'
]);

Gotchas and Tips

Pitfalls

  1. Escaping HTML: Always use ->escape(false) for columns with raw HTML to avoid XSS vulnerabilities. Prefer Blade components or sanitization for dynamic content.

  2. Query Performance: Avoid eager-loading unnecessary relationships in server-side processing. Use select() to limit columns:

    $table->of(App\Models\User::query()->select('id', 'name', 'email'));
    
  3. Tailwind Class Conflicts: If using custom Tailwind classes, ensure they don’t conflict with the package’s default styles. Use unique class names or override styles in your CSS.

  4. Pagination Mismatch: Ensure pagination settings (perPage) align with your API or frontend expectations. Default is 10, but adjust as needed:

    $table->paginate(25);
    

Debugging

  • Check Logs: Enable Laravel debug mode (APP_DEBUG=true) to inspect queries and errors.
  • DD() Queries: Use dd($table->getQuery()) to debug the final query before execution.
  • View Source: Inspect the rendered HTML (View::share('html', $table->table())) to verify styling.

Extension Points

  1. Custom Views: Override the default table view by publishing assets and extending resources/views/vendor/tailwind-datatables/table.blade.php.

  2. Custom Styling: Extend Tailwind config (tailwind.config.js) to add custom colors or utilities:

    module.exports = {
        theme: {
            extend: {
                colors: {
                    'brand': '#3b82f6',
                }
            }
        }
    }
    
  3. API Integration: For SPAs, return JSON responses:

    return response()->json($table->toJson());
    
  4. Localization: Translate labels (e.g., "Showing 1 to 10 of 100 entries") by publishing the language file and extending it:

    php artisan vendor:publish --provider="Squipix\TailwindDataTables\TailwindDataTablesServiceProvider" --tag="lang"
    
  5. Event Hooks: Listen for events like datatables.querying or datatables.rendered to modify behavior:

    TailwindDataTables::listen('datatables.querying', function ($query) {
        // Modify query before execution
    });
    

Config Quirks

  • Asset Paths: Ensure tailwind-datatables assets (CSS/JS) are published to public/vendor/tailwind-datatables or update the config/tailwind-datatables.php paths.
  • Default Sorting: Set default sort columns in config:
    'default_sort' => ['name' => 'asc'],
    
  • Server-Side Timeout: Adjust config/tailwind-datatables.php server_side_timeout for large datasets (default: 30 seconds).

Performance Tips

  • Lazy Loading: Use with() for relationships only when needed:
    $table->of(App\Models\User::query()->with(['posts' => function ($query) {
        $query->where('published', true);
    }]));
    
  • Caching: Cache frequent queries or table configurations:
    $table = Cache::remember("datatable_users", now()->addHours(1), function () {
        return TailwindDataTables::of(App\Models\User::query())->make();
    });
    
  • Debounce Search: For search inputs, debounce requests to avoid excessive queries:
    // Example Alpine.js debounce
    <input x-data="{ debounce: null }"
           @input.debounce.300ms="debounce = setTimeout(() => { /* Search */ }, 300)"
           @input="clearTimeout(debounce)">
    
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