Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Matt Komarnicki Avatar asked Jan 03 '23 19:01

Matt Komarnicki


2 Answers

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']);
        });
    }
}
like image 134
krisanalfa Avatar answered Jan 05 '23 14:01

krisanalfa


Use the load() method:

auth()->user()->load('relationship');
like image 31
Alexey Mezenin Avatar answered Jan 05 '23 14:01

Alexey Mezenin