Reputation: 268
I have two relationships in my user model:
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
If I try to use in controller role relationship it works, but currency relationship brings NULL with dd($user)
$user = Auth::user()->currency;
$user = Auth::user()->role;
It has to be something with AUTH. Thank you for your help.
full User Model:
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Notifications\ResetPassword;
use Hash;
/**
* Class User
*
* @package App
* @property string $name
* @property string $email
* @property string $password
* @property string $role
* @property string $remember_token
*/
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', 'remember_token',
'role_id', 'currency_id'];
/**
* Hash password
* @param $input
*/
public function setPasswordAttribute($input)
{
if ($input)
$this->attributes['password'] = app('hash')-
>needsRehash($input) ? Hash::make($input) : $input;
}
/**
* Set to null if empty
* @param $input
*/
public function setRoleIdAttribute($input)
{
$this->attributes['role_id'] = $input ? $input : null;
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
}
my currency model:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\FilterByUser;
/**
* Class Currency
*
* @package App
* @property string $title
* @property string $symbol
* @property string $money_format
* @property string $created_by
*/
class Currency extends Model
{
use SoftDeletes, FilterByUser;
protected $fillable = ['title', 'symbol', 'money_format',
'created_by_id'];
/**
* Set to null if empty
* @param $input
*/
public function setCreatedByIdAttribute($input)
{
$this->attributes['created_by_id'] = $input ? $input : null;
}
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
}
Upvotes: 0
Views: 1731
Reputation: 401
did u mean eager loading? add with property in user model
protected $with = ['role','currency'];
Upvotes: 2
Reputation: 163758
You need to make currency_id
an integer instead of string:
$table->unsignedInteger('currency_id');
Upvotes: 1