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

FallOutBoi's avatar

Where in relationship's relation

Hi guys, i am trying to get all seller type of users using eloquent ORM. I have three tables users, roles and user_role. User table contains standard user info name, email, password, the roles table has the list of the roles that can be assigned to a user, and user_role has both id of an user and role to as foreign key. The problem is now i am trying to get all seller type of users using this query.

$users = User::with('userRole.role')->where('machine_name', 'seller')->paginate(10);

But it returns error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userRole.role.machine_name' in 'where clause' (SQL: select * from `users` where `userRole`.`role`.`machine_name` = seller)`

My User model looks like this

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'type',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'is_admin',
    ];

    public function userRole(){
        return $this->hasOne(\App\UserRole::class);
    }
}

My UserRole Model Looks like this

class UserRole extends Model
{
    protected $table = 'user_role';

    public function user(){
        return $this->belongsTo(\App\User::class);
    }

    public function role(){
        return $this->belongsTo(\App\Role::class);
    }
}

My Roles Model looks like this

class Role extends Model
{
    public $timestamps = false;

    public function userRole(){
        return $this->hasMany(\App\UserRole::class);
    }
}
0 likes
3 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

You are overcomplicating stuff:

Role::with('users')->where('macine_name', 'seller')->get();

In User and Role models add BelongsToMany relationships

// role model
public function users(): BelongsToMany
{
  return $this->belongsToMany(User::class);
}

// user model
public function roles(): BelongsToMany
{
  return $this->belongsToMany(Role::class);
}
FallOutBoi's avatar

Ahh can't believe it was this easy. So it automatically enters role_user table, i just didn't know that

bugsysha's avatar

Yeah, it can be easy if you go down the right path. 👋

1 like

Please or to participate in this conversation.