Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties

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?

like image 406
John Avatar asked Jun 02 '13 22:06

John


1 Answers

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;
like image 89
John Avatar answered Nov 20 '22 18:11

John