Laravel get model from ID with belongtoMany

14,162

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);
Share:
14,162
Oğuz Çiçek
Author by

Oğuz Çiçek

Updated on June 19, 2022

Comments

  • Oğuz Çiçek
    Oğuz Çiçek almost 2 years

    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?