It seems like there's a misunderstanding in how the logical OR operator is being used in the context of the Eloquent model events and global scopes. The || operator is not being used correctly to apply the conditional logic you're aiming for. Instead, it's being evaluated in a way that doesn't modify the query as intended.
Here's a revised solution that should work for filtering by user and allowing an admin to see everything:
parent::boot();
self::creating(function($model) {
// Only set the user_id if the user is not an admin
if (!auth()->user()->is_admin) {
$model->user_id = auth()->id();
}
});
self::addGlobalScope('filterByUser', function(Builder $builder) {
if (!auth()->user()->is_admin) {
$builder->where('user_id', auth()->id());
}
// If the user is an admin, no additional global scope is applied,
// so they see everything.
});
In the creating event, we're checking if the authenticated user is not an admin before setting the user_id. This ensures that if an admin is creating a model, the user_id is not set to an incorrect value.
In the addGlobalScope, we're applying a named scope 'filterByUser' and only adding the where condition if the authenticated user is not an admin. If the user is an admin, the query is not modified, allowing them to see all records.
Remember to import the Builder class at the top of your file:
use Illuminate\Database\Eloquent\Builder;
Also, ensure that the auth()->user() is available during the booting of the model. If it's not, because the session has not started yet (for example, during a console command), you might need to apply the global scope conditionally or within a middleware where the session is guaranteed to be started.