ymigval/laravel-model-datatable-ssp
composer require ymigval/laravel-model-datatable-ssp and publish the config (if needed) with php artisan vendor:publish --provider="Ymigval\LaravelModelDatatableSsp\ServiceProvider".datatable() on an Eloquent model instance or query with column mappings:
return Customer::datatable(['first_name', 'last_name', 'email']);
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' }
]
});
Basic CRUD Integration:
datatable() in controllers to return paginated, filtered, and sorted data for read operations.public function index(Request $request)
{
return User::datatable([
'id', 'name', 'email', 'created_at'
]);
}
Dynamic Column Mapping:
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');
}
]);
Query Scoping:
where, with, orderBy) before calling datatable():
return Post::with('author')
->where('published', true)
->orderBy('created_at', 'desc')
->datatable(['title', 'author.name', 'created_at']);
Reusable DataTable Services:
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>';
}
]);
}
}
API Resource Integration:
return response()->json(
Customer::datatable(['id', 'name', 'email'])->toArray()
);
ajax option to point to your Laravel endpoint. Ensure processing: true and serverSide: true are set.auth, admin) to restrict access.return Cache::remember('customers_datatable', now()->addHours(1), function () {
return Customer::datatable(['id', 'name'])->toArray();
});
$response = $this->get('/admin/customers');
$response->assertJsonStructure([
'data', 'recordsTotal', 'recordsFiltered', 'draw'
]);
Column Name Mismatches:
data and name in JavaScript) match the keys in your PHP mappings. Mismatches will cause silent failures or incorrect data display.dd() to inspect the response:
dd(Customer::datatable(['id', 'name'])->toArray());
Nested Relationships:
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;
}
]);
Case Sensitivity:
return Customer::datatable([
'firstName' => 'first_name', // Explicit mapping
]);
Pagination Conflicts:
lengthMenu and serverSide settings align with the package’s pagination logic. The package handles SSP pagination internally.paginate() with datatable() on the same query.Performance with Large Datasets:
datatable() can be slow for large datasets. Use database indexes and limit eager-loaded relationships:
return Order::with(['customer:id,name', 'items:id'])->datatable([...]);
Inspect Raw Data:
toArray() or toJson() to debug the raw response:
return Customer::datatable(['id', 'name'])->toJson();
data, recordsTotal, recordsFiltered, and draw keys.Check DataTable Request Parameters:
draw, start, length, search, order). Verify these are sent in the AJAX request:
console.log(data); // Log the request payload in your frontend
Enable Query Logging:
\DB::enableQueryLog();
$result = Customer::datatable(['id', 'name'])->toArray();
\DB::getQueryLog(); // Inspect the generated queries
Customizing Defaults:
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.'global_scopes' => [
\Illuminate\Database\Eloquent\Scope\PresentScope::class,
],
Extending the Package:
Datatable class by binding your own implementation in the service provider:
$this->app->bind(
\Ymigval\LaravelModelDatatableSsp\Datatable::class,
\App\Services\CustomDatatable::class
);
Handling Custom Sorting:
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);
}
]
]);
Add Custom Actions:
toArray() output:
$datatable = Customer::datatable(['id', 'name']);
$datatable->getData()->each(function ($row) {
$row->actions = '<a href="/edit/'.$row->id.'">Edit</a>';
});
return $datatable->toArray();
Integrate with Laravel Nova:
Add Search Functionality:
applySearch method in your service provider or by using closures in column mappings:
return Product::datatable([
'name',
'sku' =>
How can I help you explore Laravel packages today?