baguus

ORM belongsToMany data handling

Posted 1 year 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

User

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

Order

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

public function users() {
    return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
}

Product

public function orders() {
        return $this
->belongsToMany('App\Order','product_order')->withPivot('order_date','status','status_change','comments')
->withTimestamps();
}

OrdersController

// 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'));
}

View

<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 }}

@endforeach 

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.

Reply to

Use Markdown with GitHub-flavored code blocks.