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

Pixelairport's avatar

Scope attribute coming from another API

Hi. I hope I can explain easily what I want to do... I have a product in a table which also has a pid field, which is an external id. This id gets extra information about the product, for example the price, via an API. I also cache the information... Now I want to create a scope. For example only products which cost less than 100$. I want to do it like that:

Product::less(100)->get()

In my model, the attribute is there and it works. I have the attribute dataGrab which grabs all and another called dataGrabPrice, which gets first the whole dataGrab attribute and only returns the price.

Now I need my scope, but dont know how to do it. Is it possible to do it? I have this at the moment:

    public function scopeLess($query, $money=1000000)
    {
        $query->where('price', $money);
    }

I think problem would be, that it has nothing to do with the database. But what is the solution for this. Or can i also do it with attributes?

Hope It is clear, what I want to do. Thx for your help.

0 likes
2 replies
cwhite's avatar

Why not just do:

    public function scopeLess(Builder $query, ?int $money = null): Builder
    {
        $query->where('price', '<', $money ?? $this->dataGrabPrice);
    }

Edit:

Actually the above wouldn't work because you're trying to access an instance attribute from within the QueryBuilder, it may be easier to just use a Collection filter

$products = Product::all()
    ->filter(fn ($product) => $product->price < $product->dataGrabMoney);
1 like
Pixelairport's avatar

@cwhite Thx. That means with a filter, that i first have to load all products right? Even if I only want to show the latest 5 active products?

If that would be, than I will maybe think about another solution tomorrow.

Please or to participate in this conversation.