如何向Laravel的auth() - > user()对象+它的关系添加更多数据?

时间:2018-02-15 12:10:21

标签: php laravel laravel-5

我的user模型具有名为person_id的外键引用,引用了person表中的单个people

enter image description here

当我死去的时候转储经过身份验证的用户(dd(auth()->user())):

{"id":1,"email":"foo@bar.baz","is_enabled":1,"person_id":3,"created_at":"2017-12-12 10:04:55","updated_at":"2017-12-12 10:04:55","deleted_at":null}

我可以通过致电auth()->user()->person来访问此人,但它是原始模型。由于我不知道在哪里给我的演示者打电话,因此我无法在auth用户的电话上调用演示者方法。

调整auth()->user对象及其关系的最佳位置在哪里,以便我可以在其上应用特定模式?

谢谢, Laravel 5.5.21

2 个答案:

答案 0 :(得分:4)

使用load()方法:

auth()->user()->load('relationship');

答案 1 :(得分:3)

您可以使用global scope

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function person()
    {
        return $this->belongsTo(Person::class);
    }

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('withPerson', function (Builder $builder) {
            $builder->with(['person']);
        });
    }
}