I am trying to model a pretty straightforward relationship, between the 'Users' table and the 'User_profiles' table. Each user has a user_profile, so it's a simple one-to-one. As per the docs found @ http://four.laravel.com/docs/eloquent#one-to-one I have added the following function to my User model:
public function user_profile()
{
return $this->hasOne('User_profile');
}
and this is the relationship defined in my User_profile model:
public function user()
{
return $this->belongsTo('User');
}
I am trying to access from the controller like this:
// Get current user
$user = User::find(Auth::user()->id);
$profile = $user->user_profile;
print_r($user);
print_r($profile);
echo "User's name is: " . $user->user_profile->first_name . ' ' . $user->user_profile->last_name;
Unfortunately printing $user prints out the User model fields just fine, but doesn't show any trace of a relationship; $profile is empty. The 'relations' array is also empty, which I'm guessing should maybe be filled.
I am trying to use the 'dynamic properties' as suggested here http://four.laravel.com/docs/eloquent#dynamic-properties
Otherwise if I just go:
echo "User's name is: " . $user->user_profile()->first()->first_name . ' ' . $user->user_profile()->first()->last_name;
It works.. but I don't really like having to do that.
Any suggestions?
Ok so the problem had to do with using underscores in the class names. Laravel follows PSR 0 and 1 as outlined here.
What this means is I had to name my model class and filename UserProfile (even though my MySql table named remained 'user_profiles'), and then update my User model to have a function called userProfile().
Once I updated the naming, I could access the relationships automatically by doing something like:
$user = Auth::user();
echo $user->userProfile->first_name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With