Reputation: 131
I am using datatable yajra package in my project lravel 5.1 and wants to get data through laravel eloquent this is my suggestion model code.
public function candidate()
{
return $this->belongsTo('App\Candidate', 'suggested_user');
}
And this is controller code.
public function getBCReport()
{
$candidates = \App\Suggestion::with('candidate')->get();
return Datatables::of($candidates)
->make(true);
}
And this is my view code:
<
div class="panel-body">
<div class="candidatereport">
<div class="table-responsive">
<table class="table display" id="table_id" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</section>
<script>
$(function() {
$('#table_id').DataTable({
processing: true,
serverSide: true,
dataType: 'json',
ajax: '{!! route('datatables.candidatereport') !!}',
columns: [
{ data: 'candidate.fname', name: 'fname' },
{ data: 'candidate.lname', name: 'lname' },
]
});
});
</script>
In controller when I use this code
$candidates = \App\Suggestion::with('candidate');
According to datatable yajra documentation http://datatables.yajrabox.com/eloquent/relationships it’s not working butt when I use with
$candidates = \App\Suggestion::with('candidate')->get();
Its working butt this is not according to datatable yajra documentation. Can any one tell what is the reason behind this. Thanks
Upvotes: 0
Views: 2229
Reputation: 5135
Here you will find my detailed answer, I have mentioned, Controller method, View structure, Datatable JS code, Have a look
Upvotes: 0
Reputation: 138
When using eloquent models, the get() method is used when there are constraints added to query. In your question you want to know why that worked in the example given in documentation for yajra. And the reason is, they have returned the data table from the eloquent model itself. Whereas, you are creating the datatable at controller level. So get() method is necessary for controller to retrieve the results out of this eloquent relation.
See the link. Under the Retrieving Multiple Models, the use of get is explained.
Upvotes: 1