Isn't there a way to hardcode the default role-getter when I use that specific model?
@rene Yup! Scopes. You could create Student and Teacher models that extend your base User model, but boot a class that scopes queries to users of either type.
Example of a Teacher model:
class Teacher extends User
{
protected static function boot()
{
static::addGlobalScope(new UserTypeScope('teacher'));
parent::boot();
}
}
class UserTypeScope implements ScopeInterface
{
protected $type;
public function __construct($type)
{
$this->type = $type;
}
public function apply(Builder $builder, Model $model)
{
$builder->where('type', '=', $this->type);
$this->extend($builder);
}
public function remove(Builder $builder, Model $model)
{
$query->wheres = collect($query->wheres)->reject(function ($where) {
return $where['column'] == 'role';
})->values()->all();
}
}
Note: this was written off the cuff so you’ll have to modify for your particular schema, but it should be enough to illustrate the steps you need to take.
Usage is straightforward:
$teachers = Teacher::all(); // Users, but scoped to teacher role