3

I'm using Laravel - data tables by yajra https://github.com/yajra/laravel-datatables-docs

It works perfectly with a single table, but things get serious when I use the eloquent relationship with it. As described below in code I'm showing user name in the table, it showing user name perfectly fine but when I try to sort on User or simply search it gives me a wrong error or shows SQL error.

I have following eloquent models

class Project extends Model{
     public function client(){
      return $this->belongsTo(Client::class);
     }
}
class Client extends Model{
     public function user(){
          return $this->belongsTo(User::class);
     }
}
class User extends Model{
}

HTML

<table id="table">
    <tbody>
        <tr>
            <td>Name</td>
            <td>Start Date</td>
            <td>Target</td>
            <td>User</td>
        </tr>
    </tbody>
</table>

Javascript

$("#table").DataTable({
        processing: true,
        serverSide: true,
        autoWidth:false,
        ajax: '/projects',
        columns:[
            { data: 'project_name', name: 'project_name' },
            { data: 'start_date', name: 'start_date' },
            { data: 'target', name: 'target' },
            { data: 'client.user.name', name: 'client.user.name' }
        ]
    });

Project Controller

public function projects(){
    return Datatables::of(Proejct::with(['client.user']))
            ->addColumn("client.user.name", function($row){
                return $row->client->user->name;
            })->make(true);
}
2
  • What error do you receive? Commented Jan 9, 2020 at 14:01
  • Two problems 1)On sorting see duplicate rows and 2)when trying to search name column not found an error Commented Jan 9, 2020 at 14:18

2 Answers 2

2

It doesn't not support multi level of eloquent relationship sorting or search. So you will get data but you can't search or sort on them.

Your code seems okay and it will work perfectly for single level.

Here's more details about the issue. https://github.com/yajra/laravel-datatables/issues/993

Sign up to request clarification or add additional context in comments.

Comments

-1

return $row->client()->user()->name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.