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);
}