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

al_imran_ahmed's avatar

What is the way of adding executable eloquent query scope

In Laravel Eloquent, we can do something like:

User::active()->where('reference', $request->ref)->first()

Here active() is a scope and we can add scope for ref too:

User::active()->reference($request->ref)->first()

Here, reference is a scope defined that return builder. But in my use case I want to execute on the scope call instead of calling first();

Like:

User::active()->reference($request->ref)

I want this to return a single object or collection of objects, or anything I want. I mean I just want to to execute when I call this scope instead of calling first() or get() again after reference() method call. I don't want further query chaining on reference()

How can I achieve this? Is there any way out of the box in Laravel to do so?

0 likes
4 replies
al_imran_ahmed's avatar

@loyd

Seems you missed my point. I don't want to call first(), get(), firstOrFail() or any such executable method. I want to execute on calling reference() which will execute and won't allow any further query chaining.

Please or to participate in this conversation.