Search code examples
phplaraveldatatable

How to route in Laravel DataTables


I am new to Laravel DataTables and i am trying to insert my controller in the datatables but i am getting an exception.

How to get this done?

PS: When I use the normal route like user/items/'$users->id'/control, it works fine but I want to use the the route like UserController@edit, $user->id

public function getPost()
{
    $users= User::where('id', Auth::user()->id);
    return Datatables::of($users)->addColumn('action', function ($user) {
        return '<a href="{ action('UserController@edit', $user->id)}" title="edit" ><i class="fa fa-edit"></i></a>
                &nbsp;&nbsp;';

    })->make(true);     

}

Solution

  • Some mentions to your code:

    // this will get you only one user
    $users = User::where('id', Auth::user()->id);
    
    // therefore it does not make sense to show one user in a table, does it ;-)
    return Datatables::of($users)->make(true);     
    

    To your question:

    You need two actions: One to render the view and one to fetch the data for the datatables via Ajax (if you use ServerSide rendering)

    Assuming you want to show a list of users:

    Routes

    Route::get('users', 'UserController@index');
    Route::get('users-dt', 'UserController@indexDataTables')->name('users:dt');
    

    Controller

    public function index()
    {
        return view('users.index');
    }
    
    public function indexDataTables()
    {
        $users = User::query();
    
        return DataTables::eloquent($users)->toJson();
    }
    

    user/index.blade.php

    <script>
        $(function() {
            $('#users-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{!! route('users:dt') !!}',
                columns: [
                    { data: 'name', name: 'name'},
                ],
            });
        })
    </script>