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

Narares's avatar

How to select the data from the many-to-many relationship table that matches the desired value?

I'm still new to Laravel. I want to select a mainchallengecategories with field role_id on the table that holds the relationship that is equal to 3 because I want the user who has role_id = 3 to see the main mainchallengecategories. What should I do with my controller?

I have 4 tables

1. mainchallengecategories

  • ID
  • Name

2. users

  • ID
  • Name
  • Role

3. roles

  • ID
  • Name
  • Role

4. main_challenge_categories_role

  • id
  • main_challenge_categories_id
  • role_id

Here is MainChallengeCategories Model

public function users(){
    return $this->hasMany(User::class);
}

public function roles(){
    return $this->belongsToMany(Role::class)->withTimestamps();
}

public function main_challenge_categories_role(){
    return $this->hasMany(MainChallengeCategoryRole::class);
}

User Model

public function roles(){
    return $this->belongsTo(Role::class, 'role');
}

Role Model

public function users(){
    return $this->hasMany(User::class);
}

MainChallengeCategoryRole Model

protected $fillable=['main_challenge_categories_id', 'role_id'];

public function mainchallengecategories(){
    return $this->belongsTo('App\MainChallengeCategories','main_challenge_categories_id');
}
public function roles(){
    return $this->belongsTo('App\Role','role_id');
}

MainChallengeCategoryController

public function create(){

/$mainchallengecategories = MainChallengeCategoryRole::with('mainchallengecategories') // Eager loading ->where('role_id', '3') ->get();/

What should I do here in this function????????

    return view('user.addChallenge')
    ->with('mainchallengecategories',$mainchallengecategories);
}

Thank you for everyone's kindness here that I have always received in advance.

0 likes
1 reply
Bcrypt's avatar

Try

$model->mainchallengecategories()->where('column', $mainchllengecategories)->get();

But in the User model roles function you're passing a 'role' string which I think it should be the foreign key od that belongs to the User which is role_id.

Please or to participate in this conversation.