Reputation: 489
I have one products table and three other table(voltage,ampere,category), now products table is relate all these three table with one to many relation like voltage,ampere,category hasMany Products
and Products belongsTo voltage,ampere,category
and each table id is use as foreign key in product table like products_table : id,name,voltage_id,ampere_id,category_id
.Now how to get all the data from these table and show it in html table of products.
Product Model
public function ampere(){
return $this->belongsTo('App\Ampere');
}
public function category(){
return $this->belongsTo('App\Category');
}
public function voltage(){
return $this->belongsTo('App\Voltage');
}
Ampere Model
public function products(){
return $this->hasMany('App\Product');
}
Category Model
public function brands(){
return $this->hasMany('App\Brand');
}
public function products(){
return $this->hasMany('App\Product');
}
Voltage Model
public function products(){
return $this->hasMany('App\Product');
}
Here is my blade view
<tr>
<td class="details">
a href="#">Product name</a>
<ul>
<li><span>category</span></li>
<li><span>Ampere</span></li>
<li><span>Voltage</span></li>
</ul>
</td>
</tr>
this is what I already have tried
public function showAllProducts(){
$products=Product::all();
$products = Product::with('category','ampere','voltage')->get();
foreach ($products as $product){
echo $product->name." ";
foreach ($product->ampere as $amp){
echo $amp->name;
}
}
}
Upvotes: 0
Views: 47
Reputation: 1733
when loading multiple relationships using with, you must pass an array:
$products = Product::with(['category','ampere','voltage'])->get();
then you can directly use $product->category->name for example.
another thing that I've noticed is that you are using echo in your showAllProducts
which will not work. what you need to do it to call the view function and pass the $products using the with function.
public function showAllProducts()
{
$products = Product::with(['category','ampere','voltage'])->get();
return view("the_name_of_your_view_file")->with("products,$products);
}
now, on your view, thanks to blade we can loop on the $products
array and show every product along with his amper, voltage and category.
@for ( $products as $product )
<tr>
<td class="details">
<a href="#">{{$product->name}}</a>
<ul>
<li><span>{{$product->category->name}}</span></li>
<li><span>{{$product->ampere->name}}</span></li>
<li><span>{{$product->voltage->name}}</span></li>
</ul>
</td>
</tr>
@endfor
Upvotes: 2