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 Model Datatable Ssp Laravel Package

ymigval/laravel-model-datatable-ssp

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Run composer require ymigval/laravel-model-datatable-ssp and publish the config (if needed) with php artisan vendor:publish --provider="Ymigval\LaravelModelDatatableSsp\ServiceProvider".
  2. Basic Usage: Call datatable() on an Eloquent model instance or query with column mappings:
    return Customer::datatable(['first_name', 'last_name', 'email']);
    
  3. Frontend Integration: Ensure your DataTable is configured to use server-side processing (SSP) and point it to the endpoint returning the above response.

First Use Case

Admin Panel Data Grid: Quickly expose a model’s data to a DataTable in an admin dashboard. For example:

// routes/web.php
Route::get('/admin/customers', [CustomerController::class, 'index']);

// CustomerController.php
public function index()
{
    return Customer::datatable(['id', 'name', 'email']);
}

Pair this with a frontend DataTable initialized with:

$('#customerTable').DataTable({
    processing: true,
    serverSide: true,
    ajax: '/admin/customers',
    columns: [
        { data: 'id', name: 'id' },
        { data: 'name', name: 'name' },
        { data: 'email', name: 'email' }
    ]
});

Implementation Patterns

Core Workflows

  1. Basic CRUD Integration:

    • Use datatable() in controllers to return paginated, filtered, and sorted data for read operations.
    • Example:
      public function index(Request $request)
      {
          return User::datatable([
              'id', 'name', 'email', 'created_at'
          ]);
      }
      
  2. Dynamic Column Mapping:

    • Leverage closures for custom transformations (e.g., formatting dates, boolean flags, or computed fields):
      return Order::datatable([
          'id',
          'customer_name' => function ($field, $row) {
              return $row->customer->name;
          },
          'status' => function ($field, $row) {
              return ucfirst($row->status);
          },
          'created_at' => function ($field, $row) {
              return $row->created_at->format('M d, Y');
          }
      ]);
      
  3. Query Scoping:

    • Chain Eloquent query methods (e.g., where, with, orderBy) before calling datatable():
      return Post::with('author')
          ->where('published', true)
          ->orderBy('created_at', 'desc')
          ->datatable(['title', 'author.name', 'created_at']);
      
  4. Reusable DataTable Services:

    • Create a service class to encapsulate complex DataTable logic:
      class CustomerDataTableService
      {
          public function getDataTable()
          {
              return Customer::datatable([
                  'id',
                  'name',
                  'email',
                  'active' => function ($field, $row) {
                      return $field ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>';
                  }
              ]);
          }
      }
      
  5. API Resource Integration:

    • Return DataTable responses as JSON API resources for consistency:
      return response()->json(
          Customer::datatable(['id', 'name', 'email'])->toArray()
      );
      

Integration Tips

  • Frontend: Use DataTables' ajax option to point to your Laravel endpoint. Ensure processing: true and serverSide: true are set.
  • Authentication: Protect routes with middleware (e.g., auth, admin) to restrict access.
  • Caching: Cache frequent queries using Laravel’s cache or query caching:
    return Cache::remember('customers_datatable', now()->addHours(1), function () {
        return Customer::datatable(['id', 'name'])->toArray();
    });
    
  • Testing: Use Laravel’s HTTP tests to verify DataTable responses:
    $response = $this->get('/admin/customers');
    $response->assertJsonStructure([
        'data', 'recordsTotal', 'recordsFiltered', 'draw'
    ]);
    

Gotchas and Tips

Pitfalls

  1. Column Name Mismatches:

    • Ensure DataTable column names (data and name in JavaScript) match the keys in your PHP mappings. Mismatches will cause silent failures or incorrect data display.
    • Fix: Double-check mappings and use dd() to inspect the response:
      dd(Customer::datatable(['id', 'name'])->toArray());
      
  2. Nested Relationships:

    • Directly accessing nested attributes (e.g., author.name) may not work as expected. Use closures or with() to eager-load relationships:
      // Works:
      return Post::with('author')->datatable([
          'title',
          'author_name' => function ($field, $row) {
              return $row->author->name;
          }
      ]);
      
  3. Case Sensitivity:

    • Column names in the DataTable JavaScript config must match the case of the model attributes. Laravel’s snake_case conversion can cause issues if not accounted for.
    • Fix: Use explicit mappings or normalize case:
      return Customer::datatable([
          'firstName' => 'first_name', // Explicit mapping
      ]);
      
  4. Pagination Conflicts:

    • If using Laravel’s default pagination, ensure the DataTable’s lengthMenu and serverSide settings align with the package’s pagination logic. The package handles SSP pagination internally.
    • Fix: Avoid mixing paginate() with datatable() on the same query.
  5. Performance with Large Datasets:

    • Complex queries with datatable() can be slow for large datasets. Use database indexes and limit eager-loaded relationships:
      return Order::with(['customer:id,name', 'items:id'])->datatable([...]);
      

Debugging

  1. Inspect Raw Data:

    • Use toArray() or toJson() to debug the raw response:
      return Customer::datatable(['id', 'name'])->toJson();
      
    • Look for data, recordsTotal, recordsFiltered, and draw keys.
  2. Check DataTable Request Parameters:

    • The package expects DataTable’s SSP parameters (draw, start, length, search, order). Verify these are sent in the AJAX request:
      console.log(data); // Log the request payload in your frontend
      
  3. Enable Query Logging:

    • Temporarily enable Laravel’s query logging to debug SQL:
      \DB::enableQueryLog();
      $result = Customer::datatable(['id', 'name'])->toArray();
      \DB::getQueryLog(); // Inspect the generated queries
      

Config Quirks

  1. Customizing Defaults:

    • Publish the config file (php artisan vendor:publish --tag=datatable-config) to override defaults like:
      • default_columns: Set default columns for all DataTables.
      • global_scopes: Apply scopes globally to all DataTable queries.
    • Example config:
      'global_scopes' => [
          \Illuminate\Database\Eloquent\Scope\PresentScope::class,
      ],
      
  2. Extending the Package:

    • Override the Datatable class by binding your own implementation in the service provider:
      $this->app->bind(
          \Ymigval\LaravelModelDatatableSsp\Datatable::class,
          \App\Services\CustomDatatable::class
      );
      
  3. Handling Custom Sorting:

    • The package supports custom sorting via the sortable option in column mappings:
      return Order::datatable([
          'id',
          'total' => [
              'field' => 'total',
              'sortable' => function ($query, $direction) {
                  $query->orderByRaw("CASE WHEN total IS NULL THEN 1 ELSE 0 END");
                  $query->orderBy('total', $direction);
              }
          ]
      ]);
      

Extension Points

  1. Add Custom Actions:

    • Extend the DataTable response to include action buttons (e.g., edit, delete) by modifying the toArray() output:
      $datatable = Customer::datatable(['id', 'name']);
      $datatable->getData()->each(function ($row) {
          $row->actions = '<a href="/edit/'.$row->id.'">Edit</a>';
      });
      return $datatable->toArray();
      
  2. Integrate with Laravel Nova:

    • Use the package to power Nova’s detail tables or custom cards by returning DataTable responses in Nova tool methods.
  3. Add Search Functionality:

    • Customize search behavior by overriding the applySearch method in your service provider or by using closures in column mappings:
      return Product::datatable([
          'name',
          'sku' =>
      
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium