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

dani94's avatar

Any pretty solution for this?

I have Order Model, which has products relationship and products have category relationship. I need to get a function in my model to get single product with a static category.

Im doing the next code in Order.php, my model, but i dont like it.

`` public function mainProduct() { foreach ($this->products as $product) if ($product->category_id == 1) return $product; }

0 likes
2 replies
JoshP's avatar

How about something like this:

In Order.php

public function products() {
    return $this->hasMany(Product::class);
}

In Product.php

public function scopeOfCategory($query, $categoryId) {
    return $query->where('category_id', $categoryId);
}

And then use it with:

$mainProduct = $order->products()->ofCategory(1)->get();
// or, if you only expect to get one
$mainProduct = $order->products()->ofCategory(1)->first();
1 like
Azik's avatar

or do it similar method

public function mainProduct()
    {
        $this->products->each(function ($product) {
            return $product->where('category_id', 1);
        });
    }

Please or to participate in this conversation.