Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get model from ID with belongtoMany

I'm building an application using Laravel 4 but have some problems with the pivot tables.

there are 3 tables Categories , Products , products_categories (pivot)

Category model

public function product()
{
    return $this->belongsToMany('Product', 'products_categories');

}

Products Model

public function category()
{
    return $this->belongsToMany('Category', 'products_categories');
}

products_categories table has product_id and category_id columns.

What I want is take all products in this category and list them in views

$category = Category::where('id' , '=' , '7')->first();

    foreach($category->product as $product){

        echo $product->id;
    }

I can see product ids related with particular category but when I want to use it to get all product itself like:

    $category = Category::where('id' , '=' , '7')->first();

    foreach($category->product as $product){

        $product = Product::where('id' , '=' , $product->id )->get();
    }

    return View::make('index')->with('product',$product);

it doesn't work :( with this error

Trying to get property of non-object

I tried this

$category = Category::where('id' , '=' , '7')->first();

    $product = array();

    foreach($category->product as $product){

        $product[] = Product::where('id' , '=' , $product->id )->get();

    }

    return View::make('index')->with('product',$product);

this time it throws this error

Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()

How can I solve this?

like image 976
Oğuz Çiçek Avatar asked Feb 24 '15 23:02

Oğuz Çiçek


1 Answers

The immediate issue is that you're trying to reuse your iterator variable from the foreach loop. This is leading to your unexpected results.

foreach($category->product as $product) {
                              ^^^^^^^^
    $product = Product::where('id' , '=' , $product->id )->get();
    ^^^^^^^^
}

However, there is no need to do any of that. $category->product is already a Collection of the Eloquent Product models. There is no need to try and retrieve the individual products again; you already have them.

If you're trying to pass this Collection to the view, you could just do:

return View::make('index')->with('product', $category->product);

Also, as a side note, if you're trying to find a record by the id, you can use the find() method:

$category = Category::find(7);
like image 117
patricus Avatar answered Oct 21 '22 16:10

patricus