Search code examples
laraveleloquentdatatablesyajra-datatable

laravel get parent data from child relationship


Hi i have this relationship between Customers and Claims

Customers Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'contr_nom',
        'contr_cog',
        'benef_nom',
        'benef_cog',
        'email',
        'polizza',
        'targa',
        'iban',
        'int_iban',
        'cliente',
    ];

    public function claims()
        {
            return $this->hasMany(Claims::class);
        }
        
    public function refunds()
    {
        return $this->hasManyThrough(Refunds::class, Claims::class);
    }

}

Claims model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Claims extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'dossier',
        'date_cla',
    ];

    public function refunds()
        {
            return $this->hasMany(Refunds::class);
        }           
        
    public function customers()
        {
            return $this->belongsTo(Customers::class,'customers_id');
        }           

}

I need to put some information from claims and from customers in a datatable

They have a parent-child relationship as first and second columns of datatables i put id and dossier from Claims table, but how i can get for example contr_nom, contr_cog, email, polizza, etc. from Customer table for each dossier?

I tried with this controller

class ComptaController extends Controller
{
    
    public function index(Request $request){

        if ($request->ajax()) {
            $data = Claims::with('customers')->get();

            /*Cannot access to  Customers from $data but i can see in the relationship*/
            dd($data->customers->contr_nom); GIVE ME ERROR

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = '<a href="javascript:void(0)" class="edit btn btn-success btn-sm">Edit</a> <a href="javascript:void(0)" class="delete btn btn-danger btn-sm">Delete</a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    
    return view('pages.compta');

    }
    
}

but i cannot access to customers data for each dossier.. Thx.


Solution

  • foreach($data->customers as $customer){
        dd($customer->contr_nom);
    }
    

    or

       Claims::with(array('customer'=>function($query){
            $query->select('id','contr_nom');
        }))->get();