I trying to get Product groups and products and show it to blade in laravel like :
x1 (category) xx1 (product) xx2 (product) xx3 (product) xx4 (product)
z1 (category) zz1 (product) zz2 (product)
here is my product group model:
public function products()
{
return $this->belongsTo(ProductModel::class, 'id');
}
and here's my product model :
public function product_groups()
{
return $this->hasMany('App\Models\ProductGroupModel','group_id');
}
here's my controller :
public function products()
{
$groups = ProductGroupModel::with(['products'])->get();
return view('admin.products', ['groups' => $groups]);
}
and here's my blade :
@foreach($groups as $group)
<tbody >
<tr>
<td >
<div >
{{$group->name}}
</div>
<a href="#" >
<i ></i>
</a>
<a href="?action=editgroup&ids=14">
<i ></i>
</a>
</td>
</tr>
</tbody>
<tbody>
@foreach($group->products as $products)
<tr>
</td>
<td>
<div >
<div >
<a href="#">
<h6 >
</h6>
<p >{{$products->name}}</p>
</a>
</div>
</div>
</td>
<td>
<p ><a href="#">xx</a></p>
<p ><a href="#">xx</a></p>
</td>
<td>
<p >44</p>
<p >33</p>
</td>
<td >
</td>
<td >
<a href="#">
<p > <i ></i> </p>
<p >show</p>
</a>
</td>
</tr>
@endforeach
</tbody>
@endforeach
when I want to show products name in second foreach I get this error
Attempt to read property "name" on bool
And I really don't know what's wrong
CodePudding user response:
You make a mistake in products (plural) method, I assume it should one to many relationship
public function products()
{
return $this->hasMany(ProductModel::class, 'fk_id', 'local_key');
}
CodePudding user response:
the Products Relationship in Product Group Model is HasMany Types
public function products()
{
return $this->HasMany(ProductModel::class,$foreignKey,$localKey);
}
$foreignKey in Products related to Product Group
$localKey=Product Group ID