DolDurma
DolDurma

Reputation: 17301

Laravel relationship is returning null

i want to create simple Relationships for find user's profile information in database with User model.

in User.php i have:

class User extends Eloquent implements UserInterface, RemindableInterface {
    ...
    public function profile() {
        return $this->hasOne('UserProfile');
    }
    ...
}

and in model/UserProfile.php:

class UserProfile extends Eloquent{

    protected $table='user_profile';
    public function user() {
        return $this->belongsTo('User');
    }
}

in database users.user_id and user_profile.user_id is 1000.

I want to access to user profile with this line in controller:

public function getIndex()
{

    $profile = $user->profile;
    dd( $profile );
    die;
}

Result of dd() is :

NULL

whats my Relationship problem?

Upvotes: 3

Views: 4934

Answers (4)

ybom
ybom

Reputation: 21

For me, the solution was eager loading just as @zwacky suggested:

or load them later with lazy-loading:

>$user = Auth::user();
>$user->load('user_profile');

This will do the solution when user_profile has just been created and you need to access user_profile through $user in another part of your code. Looks like laravel does not update the parent model immediately.

Upvotes: 0

Arda
Arda

Reputation: 6926

I had suffered from the same issue and the reason was there was a whitespace after the column which would be used as relation. Simply deleting it solved. May not be related to your question directly, but I believe this may save some hours of people who reach this page through a search engine.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

For your users table you are using a different primary key other than id as expected so in your User model you should explicitly declare the protected $primaryKey = 'user_id' and also you may use this:

// Not tested with same foreign and local key
return $this->hasOne('UserProfile', 'user_id', 'user_id');

But it's better to keep the both keys different, probably you can rename the users.user_id to users.id. If you rename the users.user_id to users.id then everything will work without any changes at all.

Upvotes: 1

Simon Wicki
Simon Wicki

Reputation: 4059

looks like the relationships aren't loaded.

either try loading them by using eager-loading

User::with('user_profile')->get();

or load them later with lazy-loading:

$user = Auth::user();
$user->load('user_profile');

also since you're using another primary key property than id, you need to specify it (or in your relation declaration):

protected $primaryKey = 'user_id';

Upvotes: 4

Related Questions