How to pass route parameter in datatable function in laravel?

Member

by addison , in category: PHP CMS , 6 months ago

How to pass route parameter in datatable function in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 6 months ago

@addison 

In order to pass route parameters in the datatable function in Laravel, you can do the following:

  1. Define the route with parameters in your routes/web.php file:
1
Route::get('/data/{parameter}', 'DataController@index')->name('data.index');


  1. In your DataController, pass the parameter to the function that retrieves and returns data to the DataTable:
1
2
3
4
5
public function index($parameter) {
    $data = Model::where('parameter', $parameter)->get();

    return DataTables::of($data)->make(true);
}


  1. In your blade view, initialize the DataTable and pass the route parameter as a data attribute:
1
2
3
<table id="data-table" data-parameter="{{ $parameter }}">
  <!-- DataTable columns here -->
</table>


  1. Finally, in your DataTables script, retrieve the route parameter from the data attribute and pass it in the AJAX call:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$(document).ready(function() {
    var parameter = $('#data-table').data('parameter');

    $('#data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("data.index") }}',
            data: { parameter: parameter }
        }
    });
});


By following these steps, you can pass route parameters to the DataTable function in Laravel.