Ad

I Can Not Access The Array That I Attached To My Pivot Table?

- 1 answer

I am using Many to Many relationships between Students and Packages which generate student_package pivot table. And I attached some extra variables, but I can not access them in my view.

Here is my code

Controller

$student->packages()->attach($request->package_id, ['paid' => '1','transaction_id'=>$transaction_id, 'amount' => $request->amount]);

View

@foreach ($student->packages as $package)
    <tr>
        <td> {{$package->id}} </td>
        <td> {{$package->name}} </td>
        <td> {{$package->amount}} </td>
        <td> {{$package->no_hours}} </td>
        <td> {{$package->transaction_id}} </td>
        <td> {{$package->paid}} </td>
                                                    
    </tr>
@endforeach

I can't access the extra parameters only. the rest are accessible.

Ad

Answer

1) Add columns that you need to withPivot() method of belongsToMany relation:

public function packages()
{
    return $this->belongsToMany(Package::class)->withPivot('paid', 'transaction_id', 'amount');
}

2) Then access pivot columns trough ->pivot property.

@foreach ($student->packages as $package)
    <tr>
        <td> {{$package->id}} </td>
        <td> {{$package->name}} </td>
        <td> {{$package->pivot->amount}} </td>
        <td> {{$package->no_hours}} </td>
        <td> {{$package->pivot->transaction_id}} </td>
        <td> {{$package->pivot->paid}} </td>
    </tr>
@endforeach
Ad
source: stackoverflow.com
Ad