[英]How I can add more data to Laravel's auth()->user() object + it's relationships?
我的user
模型具有名為person_id
外鍵引用,該引用引用了我的people
表中的單person
。
當我死了並轉儲經過身份驗證的用戶( 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
來訪問person,但它是一個原始模型。 Person的Presenter不適用於它因此我無法在auth用戶的人身上調用presenter方法,因為我不知道在哪里調用我的演示者。
調整auth()->user
對象及其關系的最佳位置在哪里,以便我可以對它們應用特定的模式?
謝謝,Laravel 5.5.21
。
使用load()
方法:
auth()->user()->load('relationship');
您可以使用全局范圍 :
<?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']);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.