My user
model has foreign key reference called person_id
that refers to a single person
in my people
table.
When I die & dump the authenticated user (dd(auth()->user())
) I get:
{"id":1,"email":"[email protected]","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}
I can access person by calling auth()->user()->person
however it's a raw model. Person's Presenter is not applied to it hence I can't call presenter methods on auth user's person because I don't know where to call my presenter.
Where is the best place to tune up auth()->user
object and it's relationships so I can apply specific patterns on them?
Thanks,
Laravel 5.5.21
.
You can use 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']);
});
}
}
Use the load()
method:
auth()->user()->load('relationship');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With