Server-side export (Buttons) with separate index and data route and controller functions #3151
-
First of all, thanks for this package; I especially like the DataTables service class and the diminishing need for custom javascript. I'm using Laravel 10 and yajra/laravel-datatables 10.1 (with all plugins). When I use a single route for Laravel Datatables, exporting data to csv/excel via the Buttons plugin works fine. But, since my project renders views to json and processes them client-side I have to separate the index view and data - calling my custom index controller function for data makes no sense to Laravel DataTables. I attempted the separation in the following way (code reduced to minimum): Routes Route::any('foo/view/index', [FooController::class, 'fooIndex'])->name('foo.view.index');
Route::any('foo/data', [FooController::class, 'fooData'])->name('foo.data'); FooController.php public function fooIndex (Request $request, FooDataTable $dataTable)
{
$view = $dataTable->render('foo.index');
// the view is rendered to json and returned here via the custom handleAjax() function
return $this->isAjax ? $this->handleAjax($view) : $view;
}
public function fooData (Request $request, FooDataTable $dataTable)
{
return $dataTable->ajax();
} FooDataTable.php public function html () : HtmlBuilder
{
return $this->builder()
->ajax([
'url' => route('foo.data'),
'type' => 'POST',
'data' => [
'_token' => csrf_token(),
],
])
// skipping table id, columns, buttons config, etc. This works fine as far as opening the view and building the DataTable is concerned, but when the export buttons are used, json data is returned (nuking my project) instead of a separate file download. So, my question: Is there a way to use server-side export via buttons while using a separate data route? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The export function is currently handled using the public function fooData (Request $request, FooDataTable $dataTable)
{
return $dataTable->render('dummy.view');
} |
Beta Was this translation helpful? Give feedback.
The export function is currently handled using the
render
method. Given this, you can use: