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?