I'm using Laravel datatables on a website.
Data is loaded through AJAX. On my frontend code I select which columns the table needs:
var dataTable = $('#products-table').DataTable({
serverSide: true,
ajax: {
'url': '{!! route('myroute') !!}',
},
columns: [
{data: 'brand_model', orderable: false},
{data: 'status', className: 'dt-body-center', orderable: false},
{data: 'sale_price', className: 'dt-body-right'},
{data: 'image_url', orderable: false, className: 'table-image'},
{data: 'actions', orderable: false, className: 'table-actions'}
],
order: [[1, "desc"]]
});
On the backend, I'm currently building the response as follows:
$products = $user->products(); // Eloquent relationship
return DataTables::of($products)
->editColumn('status', function ($product) { ... })
->addColumn('actions', function ($product) { ... })
...
->make(true);
Everything is displayed correctly, but I analyzed the ajax response and I noticed that every column and even the user
relationship of every product is returned. Basically, for each row in the table I return a whole bunch of useless data that should not be available on the frontend.
Is there a way to force the datatable builder to only include those fields and not everything else?
The only thing I could do is to only select the desired fields in the eloquent query:
$products = $user->products()->select(['status', 'image_url', ... ]);
But this solution is not feasible, because I need most of the fields and relationships to build the additional columns (i.e. actions
). The field should be filtered after the required columns are built.
While an automatic solution would be perfect, I would also consider a manual solution (where I have to manually specify which fields to include in the response)