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.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
2. users
3. roles
4. main_challenge_categories_role
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.
Please or to participate in this conversation.