Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CrastyCrap's avatar

make model get only users of specific type

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

0 likes
7 replies
Snapey's avatar

create Teacher model

tell it to use the users table

add a global scope that adds ->where('type',3); to every query on the Teacher model

https://laravel.com/docs/8.x/eloquent#anonymous-global-scopes

<?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);
        });
    }
}
3 likes
drewdan's avatar

@Snapey I like this approach to handle things like this. Seems a really clean way to do it.

Snapey's avatar

@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.

CrastyCrap's avatar

@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

Snapey's avatar

@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.

1 like
drewdan's avatar

@Snapey in the case of users, I agree, having a belongsToMany relationship with a role table would be a stronger pattern to use.

Please or to participate in this conversation.