I'm having a problem with laravel's OnetoMany feature. My goal is to retrieve the different codes of a user : Code Model :
public function users(){
return $this->belongsTo('App\Users');
}
User model :
public function code(){
return $this->hasMany('App\Code');
}
And my controller :
$users= Users::find($id);
dd($users->codes);
But this function is returning "null". I can retrieve my user's data but not the associated codes. Thank for your help !
you should rename the code relation in user model to be plural:
public function codes()
{
return $this->hasMany('App\Code');
}
and then:
$user= Users::with('codes')->find($id);
dd($user->codes);
please note that find retrieve only one user so name the variable '$user' not '$users'