You need to clarify what you need; what does "add a specific category number to show the number of specific products" mean? What, if any, relations are defined on the models?
Help adding category number
Hello my friends
I hope I am in the right place
I have this code
And I am looking for a way to add a specific category number to show the number of specific products
I hope you understand my request and help me and thank you in advance.
@foreach (\App\Models\Product::isPublished()->latest()->take(Number of products)->get() as $product)
@include( 'frontend.default.pages.partials.products.horizontal-product-card', [ 'product' => $product, ] )
$categories = \App\Models\Category::whereIn('id', $product_categories)->get();
@foreach ($categories as $category) Category Name @endforeach
In the models, you need to declare these relationships.
// Category model
public function products()
{
return $this->belongsToMany(Product::class, 'product_categories');
}
// Product model
public function categories()
{
return $this->belongsToMany(Category::class, 'product_categories');
}
Then you have two ways to retrieve the products for a specifig category.
$category = Category::find($category_id);
$products = $category->products;
$products = Product::whereHas('categories', function ($query) use ($category) {
$query->where('id', $category->id);
})->get();
Please or to participate in this conversation.