Laravel - Automatically load Auth::user() relations

Viewed 1784

I was wondering if it's possible somehow to automatically load all Auth::user() relationships.

Auth::user() returns an instance of my App\Models\Auth\Usuario.php, and inside Usuario.php class I have some relationships with another models.

The way I'm doing it now manually loads the relations with $user->load('relation') but I need to do it in every request.

I was thinking to do something like this in my base Controller:

public function __construct()
{
    $user = Auth::user();
    $this->relation = $user->load('relation');
}

But It's not exactly what I'm looking for.

There is another/best way to load all the Auth::user() class relationships? Like middleware or something?

3 Answers

You can use the $with property on your model to declare relationships that should always be eager loaded.

From the docs:

Sometimes you might want to always load some relationships when retrieving a model. To accomplish this, you may define a $with property on the model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['author'];

    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

I'm using a view shared variable set in a middleware, so here is a example

  1. the route:

Route::prefix('accounts')->middleware(['auth', 'profile'])

  1. the middleware (profile) :

view()->share('currentUser', Auth::user()>setRelations(['profile']));

  1. in any view:

$currentUser->profile->description

I am not sure why you are manually loading relations, this should be done within your model?

Anyway to answer your question, i use a helpers.php which I add to composer autoload:-

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "files": [
        "app/helpers.php"
    ]

within this helpers file you could decalare custom global methods:-

function current_user()
{
    return auth()->user();
}
Related