Home > Mobile >  How I car write Controller function on many to many with relation attributes
How I car write Controller function on many to many with relation attributes

Time:06-02

I am working on applying many to many relations on table Accident, Car where the relations are as follows: In the Accident model:

public function car()
{
    return $this->belongsToMany(Car::class,'accident_participateds',
    'reportNo','vehicleId');
}

In-car Model

public function accidents()
    {
        return $this->belongsToMany(Accident::class,'accident_participateds',
        'vehicleId','reportNo')->withPivot(['damageAmount', 'IBAN']);
    }

I want to display the data from all 3 Models (Car, Accident,accident_participateds)My question is whether these statements are correct in the controller

public function AdminClaims()
    {
        $claim = Accident::with('car')->get();
        $details = Car::with('accidentsr')->get();
        return view('admin.AdminClaims',compact('claim','details'));
        
    }

Because when I try to display like this:

<tbody>
            @foreach($claim as $claims)
              <tr>
                <td>{{$claims->ReportNumber}}</td>
                @foreach($details as $AP)
                <td>{{$AP->vehicleId}}</td>
                <td>{{$AP->Location}}</td>
                <td>{{$AP->Date}}</td>
                <td>{{$AP->damageAmount}}</td>
                <td>{{$AP->IBAN}}</td>
            @endforeach 
              </tr>
            @endforeach

it print only ReportNumber kindly tell me where I made a mistake? enter image description here

CodePudding user response:

From what I understand, you want to display the details of Accident(claim), associated Car and data from the pivot table.

To do so you can try

public function AdminClaims()
{
    $claims = Car::with('accidents')->get();

    return view('admin.AdminClaims',compact('claims'));
        
}

And in view

@foreach($claims as $claim)
    <tr>        
        <td>{{$claim->ReportNumber}}</td>
        <td>{{$claim->vehicleId}}</td>
        <td>{{$claim->Location}}</td>
        <td>{{$claim->Date}}</td>
        <td>{{$claim->pivot->damageAmount}}</td>
        <td>{{$claim->pivot->IBAN}}</td>
    </tr>
@endforeach
  • Related