It seems like your Category hasMany Product, which means it retuns a collection, not a single product. However in your view, you're trying to access a single product on your category. You need another @foreach loop for your products.
enkay said:
It seems like your Category hasMany Product, which means it retuns a collection, not a single product. However in your view, you're trying to access a single product on your category. You need another @foreach loop for your products.
Ok, I will try,
I want to access, Each categoty products.
What I need to change?
I changed my cotroller
<?php
class HomeController extends BaseController {
public function index() {
$categories = Categorie::with('product')->get();
$products = Product::get();
return View::make('home', array(
'categories' => $categories,
'products' => $products
));
}
}
And added one more foreachloop
<select data-placeholder="Select product" style="width:350px;" class="chosen-select" tabindex="5">
<option value=""></option>
@foreach ($categories as $categorie)
{{'<optgroup value="'.$categorie->id.'" label="'.$categorie->name.'">' }}
@foreach ($products as $product)
{{'<option>'.$product->name.'</option>'}}
@endforeach
</optgroup>
@endforeach
</select>
Now do not have error!
Good thing is, I get all categories! :)
But each category, has ewery second level products.
How I get just correct products for correct categories? Thanks :)
Your controller was fine the way it was before. Edit your model and your view.
Categorie.php
<?php
class Categorie extends Eloquent{
protected $table = 'categories';
public function products() {
return $this->hasMany('Product', 'categorie_id');
}
}
view.blade.php
<select data-placeholder="Select product" style="width:350px;" class="chosen-select" tabindex="5">
<option value=""></option>
@foreach ($categories as $categorie)
{{'<optgroup value="'.$categorie->id.'" label="'.$categorie->name.'">' }}
@foreach($categorie->products() as $product)
{{'<option>'.$product->name.'</option>'}}
@endforeach
@endforeach
</select>
@foreach($categories->products() as $product)
{{ $product->name }}
@endforeach
This code gives me error
Symfony \ Component \ Debug \ Exception \ FatalErrorException Call to undefined method Illuminate\Database\Eloquent\Collection::products()
When I change code to Remove () at the end of product, I get!
@foreach($categories->products as $product)
{{ $product->name }}
@endforeach
This error!
ErrorException Undefined property: Illuminate\Database\Eloquent\Collection::$products (View:C:\xampp\htdocs\laravel\app\views\home.blade.php)
I know this is an old thread, but I thought I would reply to the last post.
@LOGINGRUPA you are getting the error because this line:
@foreach($categories->products() as $product)
should be this:
@foreach($categorie->products() as $product)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community