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?
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
Route::prefix('accounts')->middleware(['auth', 'profile'])
view()->share('currentUser', Auth::user()>setRelations(['profile']));
$currentUser->profile->description
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With