Sorting by eloquent relationship in Laravel using DataTables - php

I'm trying to use DataTables to display list of Application model.
Application model has operations:
public function operations(){
return $this->hasMany('\App\Operation', 'application_id', 'id');
}
Operations model has state:
public function state(){
return $this->belongsTo('App\State', 'status_id', 'id');
}
and operation author (user):
public function user(){
return $this->hasOne('App\User', 'id', 'user_id');
}
To enable datatable i'm using this code:
$(function() {
$('#applications-table').DataTable({
language: {
"url": "/js/Polish.json"
},
processing: true,
serverSide: true,
ajax: '{!! route('applications.data') !!}',
columns: [
{ data: 'number', name: 'number', className: "vertical_middle", searchable: true},
{ data: 'operations.0.correspondence', name: 'operations.correspondence', className: "vertical_middle", orderable: false, searchable: false},
{ data: 'operations.0.comment', name: 'operations.comment', className: "vertical_middle", orderable: false, searchable: true},
{ data: 'operations.0.prognosed', name: 'operations.prognosed', className: "vertical_middle", searchable: false},
{ data: 'operations.0.state.name', name: 'operations.state.name', className: "vertical_middle", searchable: false},
{ data: 'operations.0.created_at', name: 'operations.created_at', className: "vertical_middle", type: "date", searchable: true},
]
});
});
ApplicationController is serving data using this code
$model = Application::with(array(
'operations' => function ($query) {
$query->orderByDesc('operations.created_at')->with('state')->with('user');
}
));
return Datatables::of($model)->make(true);
And finally a problem - table is rendering properly, but when I try to sort by another column than the first one I receive warning:
DataTables warning: table id=applications-table - Requested unknown parameter 'operations.0.correspondence' for row 0.
Honestly, I have no idea how to make it work.
Thank you in advance.

Fixed by using DB::table
$applications = DB::table('applications as a')
->join('operations as o', function($join){
$join->on('o.application_id', '=', 'a.id')
->on('o.id', '=', DB::raw("(SELECT max(id) from operations WHERE operations.application_id = a.id)"));
})
->join('users as u', 'o.user_id', '=', 'u.id')
->join('states as s', 'o.status_id', '=', 's.id')
->select(['a.id as a_id','a.number','o.*', 'u.name as u_name', 'u.surname as u_surname', 's.name as s_name']);
return Datatables::of($applications)->make(true);

Related

Sorting on chaining query using laravel datatables server side function

I'm trying to sorting the column named agency_name. But its not working. The full_name is perfectly working while the agency_name column is not working. So basically I trying to access the data which in the user_work_experiences table, so the way I access them is through user table and get current user work experiences. Im using yajra/datatables package. So here my table structure looks: -
Student Hostels
user_id
Users:
id
User Work Experiences
user_id
agency_name
Here the example code:
Controller:
public function getHostels()
{
$hostels = StudentHostel::with('user', 'user.userProfile', 'user.currentWorkExperience', 'status')->limit(100)->select('student_hostels.*');
return Datatables::of($hostels)
->addIndexColumn()
->editColumn('user.full_name', function (StudentHostel $hostel) {
return $hostel->user->full_name;
})
->editColumn('user.userProfile.address_1', function(StudentHostel $hostel) {
return $hostel->user->userProfile ? $hostel->user->userProfile->address_1 . " " . $hostel->user->userProfile->address_2 : null;
})
->addColumn('action', 'backEnd.hostel.datatables_action')
->orderColumn('user.full_name', function ($query, $order) {
$query->whereHas('user', function ($q) use($order) {
$q->orderBy('full_name', $order);
});
})
->orderColumn('user.current_work_experience.agency_name', function ($query, $order) {
$query->whereHas('user', function ($q) use ($order) {
$q->whereHas('currentWorkExperience', function ($q) use ($order) {
$q->orderBy('agency_name', $order);
});
});
})
->orderByNullsLast()
->make(true);
}
Views:
$('#hostel_datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('hostel.application.list') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
{data: 'user.full_name', name: 'user.full_name'},
{data: 'user.current_work_experience.agency_name', name: 'user.current_work_experience.agency_name'},
{data: 'user.userProfile.address_1', name: 'user.userProfile.address_1', orderable: false, searchable: false},
{data: 'status.base_setup_name', name: 'status.base_setup_name', orderable: false, searchable: false},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
I hope you guys can help me out. Thank you so much :)

Yajra Datatable relationship showing records in one column

Here's my ID column data structure
ID: [1,2,3,4,5,6,7,8]
Here is my controller's code.
$transaction = ExpenseEntry::with('transaction');
return DataTables::eloquent($transaction)
->editColumn('transaction', function (ExpenseEntry $expense) {
return $expense->transaction->map(function ($transaction) {
return $transaction->id;
});
})->make(true);
and Javascript Function
$(document).ready(function () {
$('#data-table').DataTable({
"ordering": false,
"processing": true,
"serverSide": true,
"ajax": '{!! route('
expense_dts ') !!}',
columns: [{
data: 'id',
name: 'id'
},
{
data: 'expense_type',
name: 'expense_type'
},
{
data: 'amount',
name: 'amount'
},
{
data: 'date',
name: 'date'
},
{
data: 'description',
name: 'description'
},
{
data: 'transaction',
name: 'transaction.id'
}
]
});
});
It is working but the problem is it is showing all the transacation.id in a table like this [1,2,3,4,5,6]
I want to get them like each id in each row with its column.

jquery-uniform radio button not working yajra-laravel-datatable package (laravel 5.6)

I use yajra-laravel-datatable (laravel 5.6).
I have put jquery-uniform radio button in datatable but that is not working.
I use $.uniform.update() but it is not working.
$(".styled_color_checkbox").uniform({
radioClass: 'choice',
wrapperClass: 'border-indigo-600 text-indigo-800'
});
Blade file code
var oTable = $('.finance_payment_datatable').DataTable({
processing: false,
serverSide: true,
ajax: {
url: '{!! route('admin.finance.invoice.datatable') !!}',
data: function (d) {
var customer_id = $(".customer_select option:selected").val();
if (typeof customer_id == 'undefined'){
customer_id = '0';
}
if (customer_id !== '0') {
d.customer_id = customer_id;
}
}
},
columns: [
{data: 'maincheck', sortable: false, orderable: false, searchable: false},
{data: 'invoice_number', name: 'invoice_number', sortable: true},
{data: 'created_at', name: 'created_at', sortable: true},
{data: 'outstanding_price', name: 'outstanding_price', sortable: true},
],
order: [[2, 'desc']],
"pagingType": "full_numbers",
"language": {
"emptyTable": "No invoice to display",
"search": '<span>Filter:</span> _INPUT_',
"lengthMenu": '<span>Show:</span> _MENU_',
},
autoWidth: false,
'fnDrawCallback': function( oSettings ) {
$.uniform.update();
}
});
Controller file code
public function invoiceDatatable(Request $request) {
$raw = Invoice::with('user')->select('invoices.*');
if ($request->has('customer_id')) {
$raw->where('invoices.user_id', $request->get('customer_id'));
}
$raw->where('invoices.outstanding_price', '>=', '1');
$datatable = app('datatables')->of($raw)
->addColumn('maincheck', function ($raw) {
return '<label><input type="radio" name="invoice" class="styled_color_checkbox outstanding_price" data-amount="'.$raw->outstanding_price.'" value="'.$raw->id.'"></label>';
})
->editColumn('created_at', function ($raw) {
return date('Y/m/d', strtotime($raw->created_at));
})
->editColumn('outstanding_price', function ($raw) {
return '$'.$raw->outstanding_price;
});
return $datatable->make(true);
}

Data table columns sort laravel 5.4

This is my table
Controller code
public function index(Datatables $datatables,Request $request)
{
$model=Customer::whereIn('group_id',[1,4]);
return $datatables->eloquent($model)->editColumn('name',function($customer){
return $customer->name.' '.$customer->last_name;
})->editColumn('type',function($customer){
return $customer->customergroup?$customer->customergroup->customer_group:'';
})->editColumn('member_since',function($customer){
return $customer->created_at->format('d-m-Y');
})->editColumn('booking_made',function($customer){
return $customer->bookings?$customer->bookings->count():0;
})->editColumn('status',function($customer){
return '<span class="label label-sm '.($customer->status?"label-green-jungle":"btn red").'">'.($customer->status?"Active":"Inactive").'</span>';
})->rawColumns(['status'])->make(true);
}
Data table script code
$(function () {
table= $('#customer-table').DataTable({
serverSide: true,
processing: true,
bFilter: false,
ajax:"{{route('admin.customer.index') }}",
columns: [
{data: 'id',name:'id'},
{data: 'name',name:'name'},
{data: 'type',name:'group_id'},
{data: 'member_since',name:'created_at'},
{data: 'booking_made',name:'booking_made'},
{data: 'status',name:'status'},
{data: 'view',searchable:false},
],
"order": [[ 0,'desc' ]],
columnDefs: [{
targets: [6,8],
orderable: false
}]
});
});
From the table(image) You can see a column Bookings Made it is the count of total booking by each customer. So the problem is that how can i sort the table according to count.I can sort customer name,and status.

Button in Laravel Datatable not rendering

I'm using Laravel 5.4 and Yajra datatable, below is my code working properly but in the 2nd action I've created, The button is not displaying but instead it display the text itself "Add Price" What am I missing ?
public function getProductDatatable()
{
$Product = Product::query();
return Datatables::eloquent($Product)
->addColumn('action', function($row) {
return 'Edit';
})
->addColumn('add_price', function($row) {
return 'Add Price';
})
->make(true);
}
Frontend Part
<script type="text/javascript">
$(function() {
$('#product-table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('product/get_product_datatable') }}',
columns : [
{data: 'id', name: 'id'},
{data: 'product_code', name: 'product_code'},
{data: 'action', searchable: false, orderable: false},
{data: 'add_price', searchable: false, orderable: false},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'}
]
});
});
</script>
You need to define rawColumns :
public function getProductDatatable()
{
$Product = Product::query();
return Datatables::eloquent($Product)
->addColumn('action', function($row) {
return 'Edit';
})
->addColumn('add_price', function($row) {
return 'Add Price';
})
->rawColumns(['add_price', 'action'])
->make(true);
}
I found this issue on github, try adding rawColumns
Datatables::eloquent($Product)
->addColumn(..)
->rawColumns(['add_price']);

Categories