Parent Table
users
schema | 'id','email','pass'
Relationship
public function profile()
{
return $this->hasOne('App\Profile','user_id');
}
Other Table
profiles
schema | 'id','user_id'/*foreign key to users table */ ,'address','city'
Relationship
public function user()
{
return $this->belongsTo('App\User','id');
}
I'm querying Profile model and would like it to eagerload with User model.
public function edit($id){
$profile = \App\Profile::with('user')->where('id','=',$id)->get();
dd($profile);
}
So that I can load the profile of the user for editing, alongwith the details data from User model like email & pass etc.
This Returns a null relation for user ??
Also, in blade while acessing $profile->user->email gives error
Undefined property: Illuminate\Database\Eloquent\Collection::$user (View: C:\xampp\htdocs\laravel1\resources\views\profile\edit.blade.php)
Here is the dd() output http://bit.ly/1dA0R5p
It returns null with user relation which is what i suspect causes undefined propertyerror in blade.
Is this approach possible? Are my relations correct?
P.S. Earlier I had a vice-versa case while Querying User model and eagerload Profile model and that worked.
Snippet
$users = \App\User::with('group','profile')->get(); //This was working
You receive
nullfor because your relation definition is wrong. Yourprofilemodel should beThe error is because you are trying to get the
userobject from a collection.Since you have used
get()to retrieve data you are receiving a collection of profiles, not a single profile. If you want a single profile use thefirst()method instead ofget(), else use it inside a loop.