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

Mat*_*cki 4 php laravel laravel-5

我的user模型有外键引用person_id,它指的是person我的people表中的一个。

在此处输入图片说明

当我死掉并转储经过身份验证的用户 ( 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}
Run Code Online (Sandbox Code Playgroud)

我可以通过调用访问人员,auth()->user()->person但它是一个原始模型。Person 的 Presenter 不适用于它,因此我无法在 auth 用户的人上调用 Presenter 方法,因为我不知道在哪里调用我的演示者。

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

谢谢,拉拉维尔5.5.21

kri*_*lfa 5

您可以使用全局范围

<?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']);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)