Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Fadi-S's avatar
Level 1

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

0 likes
7 replies
tykus's avatar

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?

2 likes
Fadi-S's avatar
Level 1

@tykus I am trying to modify the code to select products from a specific category and not from all categories.

1 like
vincent15000's avatar
Level 63

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();
2 likes
Fadi-S's avatar
Level 1

@vincent15000

Sorry to bother you, you said there are two ways to display.

I found this relationship ad in the ready files.

Can you please give me a complete code as an example to display products from a category by category number?

Fadi-S's avatar
Level 1

Thanks for your help.

I expect my problem needs a professional programmer, as I am a beginner.

Thank you very much.

1 like

Please or to participate in this conversation.