That depends how your attribute is determined. Could you "calculate" it using SQL? But if you absolutely want to use an accessor there is no other way.
Jul 10, 2021
2
Level 5
Query model's attribute that is a accessor
Hello everybody,
I got some custom accessor on my model like this:
public function getRandomAttribute(): ?string
{
return "Test";
}
Now I'd like to query this randomAttribute:
Item::whereRandom("Test")->first()
This does not work - of course, as Eloquent is querying the database and this value is not existing in my database.
So I just wondered, if:
collect(Item::all())->where('random', 'Test')->first();
is the best and most performant way to get my result.
Level 55
@ahoi when you query database you can't use accessors, that's true. You need to query by database columns
In you example your accessor to don depends on value, so, we will not be able to suggest the solution for you
PS: Item::all() returns Collection instance, you don't need to collect it
1 like
Please or to participate in this conversation.