I have two tables:
Products:
- id
- name
- category_id
- Description
Categories:
- id
- name
How can I display (foreach) all products in a certain category ?
Product Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name', 'category_id', 'description',];
public function category()
{
return $this->belongsTo(Category::class);
}
}
Category Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name',];
public function products()
{
return $this->hasMany('App\Product','category_id');
}
}
CategoryController :
public function show($id)
{
//
$categories = Product::where('category_id', '=', $id)->get();
return view ('categories.show',compact('categories'));
}
Show.blade.php :
@foreach ($categories as $product)
{{$product->category_id}}
@endforeach
{{ $product->category->name }}
$category = Category::with('products')->find($category_id);
After that, your products will be a collection under$category->products();
- Farid