I have a model with three visibilities;
- public (for everyone, regardless of authentication status)
- private (only for the creator)
- auth (for every authenticated user)
To simplify this logic, I figured I'd use query scopes, however I've never used them before so I'm wondering if I'm using them correctly.
My model's code (irrelevant bits omitted)
class MyModel extends Model
{
public const VISIBILITY_PUBLIC = 1;
public const VISIBILITY_PRIVATE = 2;
public const VISIBILITY_AUTH = 3;
public static function visible(): Collection
{
return self::query()
->private()->orWhere
->public()->orWhere
->auth()
->orderBy('name')
->get();
}
public function scopePrivate(Builder $query): Builder
{
return auth()->check() ? $query->where('user_id', auth()->user()->id) : $query;
}
public function scopePublic(Builder $query): Builder
{
return $query->where('visibility', self::VISIBILITY_PUBLIC);
}
public function scopeAuth(Builder $query): Builder
{
return auth()->check() ? $query->where('visibility', self::VISIBILITY_AUTH) : $query;
}
}
In a controller I can then simply call MyModel::visible(); to get all models the specific user can see.
My question is, is this a valid way of using query scopes? My main concern is scopePrivate since I'm not actively checking for self::VISIBILITY_PRIVATE, only records where user_id is the currently authenticated user's id. My tests pass, but that might as well indicate an error in my tests.