Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to edit column on laravel?

I'm working with Laravel 5.1 + datatables (http://datatables.yajrabox.com/).

I need to edit column user_id and show the firstname and lastname from relationships.

There is my code.

public function getOrders(Request $request){
  if($request->ajax()) {
       $orders = Order::with('call', 'contact.company', 'campaign')
                        ->Client()->Finished()->get();

       return Datatables::of($orders)->editColumn('user_id', 
                 function ($orders) {
                      return $orders->User->firstname.' '.$orders->User->lastname;
                  })->make(true);
   }                    

   return view('global/orders');
}

And there is my datatables.js call:

var oTable = $('#orders-data').dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": '/history/orders',
        "columns": [
            { data: 'created_at', name: 'created_at' },
            { data: 'user_id', name: 'user_id' },
            { data: 'call.phone', name: 'phone' },
            { data: 'contact.first_name', name: 'first_name' },
            { data: 'contact.last_name', name: 'last_name' },
            { data: 'contact.company.name', name: 'company' },
            { data: 'contact.address', name: 'address' },
            { data: 'contact.postal', name: 'postal' },
            { data: 'contact.city', name: 'city' },
            { data: 'contact.country', name: 'country' },
            { data: 'campaign.name', name: 'name' },
            { data: 'call.call_length', name: 'call_length' },
            { data: 'call.comment', name: 'comment' },
            { data: 'call.status', name: 'status' },
            { data: 'call.full_record', name: 'full_record' },
            { data: 'action', name: 'action', orderable: false, searchable: false }
        ]
});

But on this $orders->User->firstname I got 10 queries

select * from `users` where `users`.`id` = 'x' limit 1

How to edit columns with relationships on $orders = Order::with('user', 'call', 'contact.company', 'campaign')->Client()->Finished()->get(); ?

like image 543
Haroldas Avatar asked Nov 12 '15 15:11

Haroldas


2 Answers

Solution was User relationship to be lowercase:

return Datatables::of($orders)
           ->editColumn('user_id', function ($orders) {
                  return $orders->user->firstname.' '.$orders->user->lastname;
           })->make(true);

Here is solution doc: https://laravel.com/docs/5.2/eloquent-relationships#eager-loading

like image 126
Haroldas Avatar answered Nov 15 '22 07:11

Haroldas


Did you tried this ?

return Datatables::of($orders)
->editColumn('user_id', {{ $orders->User->firstname.' '.$orders->User->lastname }})
->make(true);

Yours sincerely,
Flemming

like image 3
Flm Avatar answered Nov 15 '22 08:11

Flm