Why you can't just add global scope to a model? Why utilizing retrieved event at all?
protected static function booted(): void
{
static::addGlobalScope(new OrderByPriorityScope);
}
https://laravel.com/docs/12.x/eloquent#applying-global-scopes
I write a trait in laravel named prioritiable and I add a global scope to the query to sort the query result based on priority value
The problem is the scope add the order by SQL clause to all SELECT, DELETE , UPDATE , INSERT but I want to just to have the scope on select
so I did this
trait Prioritiable
{
protected static function bootPrioritiable(): void
{
static::retrieved(function ($model) {
$model->addGlobalScope(OrderByPriorityScope::class);
});
}
}
The problem solved for first, find , firstOrFail , findOrFail but the scope does not work for get , all , paginate, since I think these three functions do not fire the retrieved event
the AI says use $builder->getQuery()->type == 'select' in the scope apply function but the type does not exists and throws error
@sajadsholi When a query is being built, it doesn't "know" for what operation it will be applied.
Post::where('name', 'some name')->orderBy('username')->get();
^
the query doesn't know here if |
it will SELECT or UPDATE or DELETE |
And when retrieved event is dispatched, the data is already retrieved from DB and it's too late to apply a scope.
I think you have two options:
::withoutGlobalScope(OrderByPriorityScope::class) for queries that should NOT be scoped.Please or to participate in this conversation.