user5405648
user5405648

Reputation:

Laravel HasOne relationship empty

I am trying to create a relationship between Player and Roleplay and its returning null. I know for a fact it should be working because the following code works perfectly:

Roleplay::find(Auth::user()->id);

And returns the correct data, a full array of the correct data.

When trying to access it this way:

Auth::user()->roleplay->user_id;

It doesn't work, can someone help me find out why?


How do you know its empty?
Because {{var_dump(Auth::user()->roleplay)}} in blade view returns EMPTY

When using it the view I also get a undefined error. Primary key of roleplay table (srp_user_statistics) is user_id, and the primary key of player table (users) is id

here is the code:

Player:
<?php
namespace App\Database\Frontend\User;

use Hash;
use Eloquent;
use \Illuminate\Auth\Authenticatable;
use \Illuminate\Contracts\Auth\Authenticatable as Authentication;

class Player extends Eloquent implements Authentication
{
    use Authenticatable;

    protected $primaryKey   = 'id';
    protected $table        = 'users';
    public $timestamps      = false;
    protected $fillable     = [];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    public function setUsernameAttribute($value)
    {
        return $this->attributes['username'] = $value;
    }

    public function roleplay()
    {
        return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id');
    }
}

Roleplay:

use Eloquent;

class Roleplay extends Eloquent
{
    protected $primaryKey   = 'user_id';
    protected $table        = 'srp_user_statistics';
    public $timestamps      = true;
    protected $fillable     = [];

    public function user()
    {
        return $this->belongsTo('App\Database\Frontend\User\Player', 'user_id', 'id');
    }

    public function government_role()
    {
        return $this->belongsTo('App\Database\Frontend\Roleplay\GovernmentRole', 'government_id');
    }
}

Upvotes: 0

Views: 1472

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

I thinks you should add 'id' to hasOne() in the User model

public function roleplay()
{
    return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id', 'id');
}

And remove 'id' from belonsTo() in Roleplay model.

Side notes

This working

Roleplay::find(Auth::user()->id);

Is not a guarantee your relationships are set properly. All it does is

Roleplay::find(1); //$user->id returns an integer.

Upvotes: 0

Related Questions