Search code examples
phpdatabaselaravelmany-to-manyrelationship

Laravel - Many To Many


I have two main tables with relationships many to many and a pivot table.

Tables

Model Product

public function orders()
{
    return $this->belongsToMany('App\Order');
}

Model Order

public function products()
{
    return $this->belongsToMany('App\Product', 'OrderDetails');
}

And

$orders = Equipment::all();

@foreach($orders as $order)
    @foreach($order->products as $product)
        {!! $product->name !!} //it works
        // How to print the value of the quantity?
    @endforeach
@endforeach

What should I do to print the value of the quantity?


Solution

  • Try ->pivot->quantity:

    {!! $product->pivot->quantity !!}
    

    Also, add withPivot to a ralationship:

    return $this->belongsToMany('App\Product', 'OrderDetails')->withPivot('quantity');
    

    https://laravel.com/docs/5.2/eloquent-relationships#many-to-many