Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Automatically load Auth::user() relations

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?

like image 946
Fantasmic Avatar asked Oct 19 '25 09:10

Fantasmic


2 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');
    }
}
like image 189
Remul Avatar answered Oct 20 '25 22:10

Remul


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

like image 26
Mouloud Avatar answered Oct 20 '25 23:10

Mouloud