2 years ago

ORM belongsToMany data handling

Posted 2 years ago by baguus

Hi everyone I'm a bit stuck with displaying data from many to many related data. I know this must have been answered many times but I can't find the right answer for me. I have 5 tables: users, orders, products and the pivot tables user_order and order_product.

Model relations


public function orders() {
        return $this


public function products() {
        return $this ->belongsToMany('App\Product','product_order')->withPivot('product_id','order_id','quantity')

public function users() {
    return $this


public function orders() {
        return $this


// Adding Items - This works. Is this the correct approach or is there a "better" way?

public function additem(Request $request) {

$order = Order::findOrFail($orderId);

$order->products()->save($order, [
                    'product_id' => $request['productId'],
                    'order_id' => $request['orderId'],
                    'quantity' => $request['quantity']]);

return back();

// display cart

public function show(Request $request, $userId) {

//  1. TODO get order ID from user ID

// get data 

$orders = Order::with('products')->findOrFail(1);
// I'm stuck here. Do I need a separate query to get all products from specific order?

return view('orders/view', compact('orders'));


<h1>Order {{ $orders->id }}<h1>

@foreach ($orders as $order)

Product id: {{ $order->products()-> index}}
Product name: {{ $order->products()-> name}}
Product price: {{ $order->products()-> price}}
Quantity: {{ $order->products()-> quantity}}  // can this be mixed?
Total: {{ ($order->products()-> quantity * $order->products()->price }}


How can I get all the data of a specific order? (Product id, Product name, Product price, Quantity) ?

Thank you for your time.

Please sign in or create an account to participate in this conversation.