Relationship not working. Foreach. Laravel

So I have defined relationship between OrderProduct.php and 'Product.php' models like this:

OrderProduct.php:

public function product()
{
    return $this->belongsTo('App\Product');
}

Product.php

public function order()
{
    return $this->belongsTo('App\OrderProduct');
}

OrderController function

public function orderShow($id)
{
    //$order = Order::where('id', $id)->first();
    $products = OrderProduct::where('id', 32)->first();
    return view('admin.orders.show', compact('order', 'products'));
}

When I do this foreach:

 @foreach($products as $product)
                    <?php dd($product) ?>
 @endforeach

I get Invalid argument supplied for foreach() How to fix this ?

Upvotes: 0

Views: 425

Answers (3)

Rahul Katara
Rahul Katara

Reputation: 1

you should try like this..

 public function orderShow($id)
    {
        //$order = Order::where('id', $id)->get();
        $products = OrderProduct::where('id', 32)->with('product')->get();
        return view('admin.orders.show', compact('order', 'products'));
    }

Upvotes: 0

huuuk
huuuk

Reputation: 4795

You've got only first record from set.
Try

public function orderShow($id)
{
    //$order = Order::where('id', $id)->get();
    $products = OrderProduct::where('id', 32)->get();
    return view('admin.orders.show', compact('order', 'products'));
}

EDIT

If you need to retrieve particular record by id, use find() or even findOrFail() method (difference you can find in docs);

public function orderShow($id)
{
    // this will retrieve record with id=32 from db if it exists,
    // and throw Illuminate\Database\Eloquent\ModelNotFoundExceptio otherw
    $product = OrderProduct::findOrFail(32);

    return view( 'admin.orders.show', compact('product') );
}

then in your blade template you can access your $product info as an object, like so

{{ $product->name }}
{{ $product->otherProductProperty }}

Upvotes: 0

Vijayanand Premnath
Vijayanand Premnath

Reputation: 3605

You are giving

$products = OrderProduct::where('id', 32)->first(); 

which will fetch you only one record the result will not be a collection so you cannot do foreach for this

You can change it as

$products = OrderProduct::where('id', 32)->get();

to make it work

You need to even check the Relationship used. One will be belongs to and the other will be hasmany

Upvotes: 0

Related Questions