lundi 25 juillet 2016

Eager Load Dynamic Attribute in Laravel for jQuery Datatable

I have a Hotel Model, which hasMany Guests, which in turn has two dynamic attributes as follows.

public function getNameAttribute(){
     return $this->user->name;
}

public function getEmailAttribute(){
    return $this->user->email;
}

Now I prefer to fetch them as $hotel->guests()->with('user'). Now when I use it for Datatable, I am not able to get the name & email in the view, for obvious reasons. So my question is, Can I eager-load the name & email attributes, so that whenever the guest model gets fetched, the said attributes are available.

Please note, I don't return it asArray or asJson, hence the concept of $attributes array doesn't apply (at-least as far as I know).

The Controller has the following code:

return Datatables::of($guests)
            ->addColumn('email',function($guest){
                return $guest->email;
            })
            ->addColumn('name',function($guest){
                return $guest->name;
            })->make(true);

However, the datatable cannot search for name or email because they are not available in database.

The jquery datatable code I use is

$(function() {
$('#guest-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{!! route('guests.data') !!}',
    columns: [
        { data: 'name', name: 'name', orderable: false },
        { data: 'email', name: 'email', orderable: false},
        { data: 'mobile', name: 'mobile', orderable: false}
    ]
   });
});

I use Laravel 5 and yajra/laravel-datatables package



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire