laraveleloquentglobal-scope

Laravel Global Scope Custom Message when Not Found


In our project, we have anonymous global scope defined this way:

static::addGlobalScope('user_team', function (Builder $builder) {
  $builder->where('team_id', '=', auth()->user()->team_id);
}

It is used to show the user information related to his team only.

If we have a user, for example, not assigned to any team it gives a 404 error with a default "Not Found" message.

What I need is to have a kind of customized exception message "You are not assigned to any team".

While doing this under local scope it works this way:

public function scopeTeam() {
  $myTeam = $this->where('team_id', auth()->user()->team_id)->first();
  if (!$myTeam) {
    abort(403, 'No team assigned');
  }

  return $myTeam;
}

I need the same under a global scope.

Reading the documentation about Global Scopes here https://laravel.com/docs/9.x/eloquent#query-scopes did not help.

Same as browsing the vendor/illuminate/... folder to see how it is implemented in general.

Any thoughts?


Solution

  • Global scopes modify the query builder, and are applied internally by laravel and are expected to return void. You also dont know the query result as global scopes are applied before the query is sent to the database.

    Local scopes are methods on the model and the result is returned, either a builder to continue the query or any other value you need.

    If what you are trying to accomplish is block access to some page(s) if a user doesn't have a team yet, maybe consider doing so in a middleware https://laravel.com/docs/9.x/middleware