4

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.

2 Answers 2

5

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']);
        });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

Use the load() method:

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

3 Comments

Hey Alexey, your solution works however I have to manually call it in every controller's method where I want to use it. Where's the best place to put it so the effect will be global. Base abstract controller? Any better place?
@slick you can do this in middleware.
Or use $appends = ['relationship'] in your model. laravel.com/docs/6.x/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.