Matt Komarnicki
Matt Komarnicki

Reputation: 5422

How I can add more data to Laravel's auth()->user() object + it's relationships?

My user model has foreign key reference called person_id that refers to a single person in my people table.

enter image description here

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.

Upvotes: 4

Views: 3984

Answers (2)

krisanalfa
krisanalfa

Reputation: 6438

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

Upvotes: 5

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Use the load() method:

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

Upvotes: 4

Related Questions