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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With