Laravel Relationship on Datatable server side

Asked

Viewed 199 times

1

Would you have some way to pass the model relationship to the columns of the Datatable server side?

For example in the Datatable script:

columns: [
    { data: 'marca_id', name: 'marca_id' },
    { data: 'automovel_modelo', name: 'automovel_modelo' },
    { data: 'action', name: 'action', orderable: false, searchable: false}
],

Where the tag_id would have to receive the relationship value to display the brand name according to the ID.

Function in the model with relationship:

public function marca(){
    return $this->belongsTo('App\Models\Config\Transito\AutomovelMarca');
}

Controller that displays data:

public function getData ()
{
    $automovel_modelo = AutomovelModelo::all();

    return Datatables::of($automovel_modelo)
    ->addColumn('action', function($automovel_modelo){
        return 
            '<a href="automoveis_modelos/'. $automovel_modelo->id .'/edit" class="btn btn-xs btn-warning" title="Editar">
               <i class="fa fa-pencil"></i>
            </a>' .
            '<a onclick="deleteData('. $automovel_modelo->id .')" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
    })
    ->make(true);


    return datatables(AutomovelModelo::query())->toJson();

}

But I couldn’t figure out how to get the relationship to json.

1 answer

1


From what I understand, you want to pass the values of marca of each AutomovelModelo to the Datatable, only that you are not loading this information. For this, use the function with to carry the relationship with marca, thus:

$automovel_modelo = AutomovelModelo::with('marca')->get();

This way, you will upload all the information from marca for each AutomovelModelo.

As for displaying in your Datatable I wouldn’t know how to tell you, but, I guess if that line { data: 'automovel_modelo', name: 'automovel_modelo' }, display the information for each column of the AutomovelModelo, you would have to replace the marca_id by just marca in the columns of your script of Datatable.

References:

  • 1

    It helped a lot, actually I had to pass the argument { date: 'brand.automovel_brand', name: 'brand.automovel_brand' }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.