简体   繁体   中英

Laravel auth:user() relationship doesn't work

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;

dd($用户)

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');
}

}

您需要将currency_id设为整数而不是字符串:

$table->unsignedInteger('currency_id');

did u mean eager loading? add with property in user model

protected $with = ['role','currency'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM