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

Ifrit's avatar
Level 2

Getting an attribute to be part of a query

I would like to know if it's possible to add an attribute to be part of a query. So what I mean is that in my Product model I have an attribute function that goes like this

public function getProductInfoAttribute()
{
    return sprintf("%s > %s",
        '['.$this->id.'] '.$this->name, $this->categories()->count());
}

and what I would like is that when I run a query

$products = Product::where('enabled', 1)->get();

my attribute will be part of that query.

Hope that made sense

0 likes
4 replies
MichalOravec's avatar

Don't use relationship in accessor, you get N + 1 query problem in your case.

$products = Product::withCount('categories')
    ->where('enabled', true)
    ->get()
    ->map(function ($product) {
        $product->info = "[{$product->id}] $product->name > {$product->categories_count}";

        return $product;
    });
Snapey's avatar

no you cannot use an accessor in a query

Please or to participate in this conversation.