Search code examples
laraveleloquenteloquent-relationship

Laravel cannot use where on a table connected using belongsToMangy


I have the following model file which has a belongsToMany relation with the portal_users table.

class Role extends Model
{
    use HasFactory;
    protected $table = 'portal_roles';
    
    protected $hidden = array('created_at', 'updated_at','deleted_at');
    
    public function users()
    {
    return $this->belongsToMany(User::class, 'portal_user_roles');
    }
}

I am trying to find details of all the users that fits into a particular role using the following query

$recordobj = Role::find(15)->users->where('firstname', 'like', '%' . $searchstring . '%')->get()->keyBy('id');

It is returning empty resultset even though there are users who is having the role id as 15. Can anyone please tell me what is the problem here?


Solution

  • Change users to users():

    $recordobj = Role::find(15)->users()->where('firstname', 'like', '%' . $searchstring . '%')->get()->keyBy('id');