i have a column in table users called type and each user have type value from 1 to 3 (1: crew 2: teacher 3: student) and of course i can get all users by using user model but i want to ask if i can make model to get all users that are teachers without make any additional table what i am trying to say that i want to make teacher model get only users with type 2 how can i do that
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table='users';
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope('teacher', function (Builder $builder) {
$builder->where('type', 3);
});
}
}
@drewdan I have a problem with this approach in that it's not uncommon to have people that have multiple roles eg both 'crew' and 'teacher' or 'crew' and 'student' so in this regard, the OP is boxing themselves into a corner.
Users should be users (for authentication only), and then have one or more roles which determine what they can see and do.
@Snapey I completely agree with you but, I am using different models just to allow anyone to understand that this relationship or function work on crew or teacher or student, in the other hand I am using a privilege system to handle the actions allowed to a define user to do
@Abdalrhman You will have a problem if a user needs to be both type 2 and type 3 - they will need a different login.
Be careful when using the model if you try and create using the Teacher model for instance. It won't automatically add type 3, although you could add a model observer to add this for you.