I have a Laravel application where all users credentials are stored in users
table.
And I have multiple user roles, for each role there is a table in DB (admins, customers, ...) each one has different data.
I'm using Auth::user()
multiple times in my application, and the query is executed only once on DB (as expected).
Example:
$user1 = Auth::user();
$user2 = Auth::user();
$user3 = Auth::user();
$user4 = Auth::user();
// The query is executed only once in DB.
When I'm trying to access admin data using Admin::where('user_id', Auth::id())->first()
multiple queries are executed.
Example:
$user1 = Admin::where('user_id', Auth::id())->first();
$user2 = Admin::where('user_id', Auth::id())->first();
$user3 = Admin::where('user_id', Auth::id())->first();
$user4 = Admin::where('user_id', Auth::id())->first();
// 4 queries are executed.
I have tried to add a relationship to user model as follows:
// App\Models\User
class User extends Authenticatable
{
...
public function admin()
{
return $this->belongsTo(Admin::class, 'id', 'user_id');
}
}
When executing Auth::user()->admin()
also 4 queries are executed.
I'm facing this problem in the model. I have this example model, where I need the agent to add an attribute:
// App\Models\Card
...
public function getCurrencyAttribute() {
$user = Auth::user() // This query is executed only once for all rows.
$admin = Admin::where('user_id', Auth::id()); // This query is executed for each row (if I have 100 rows, it's executed 100 times).
...
}
...
Is there a way to cache the query as Auth::user() is cached?
CodePudding user response:
first of all, Auth::user()
is not cached, it's just stored in memory,
and whenever you say Model::where('condition')->first()
, you are telling the application to execute a query, so it will be executed, also when you say Auth::user()->admin()
, you are calling it as a method, so it will return a query builder, you should call it as a property Auth::user()->admin
, like this
try using load
method, Auth::user()->load(['admin'])
, it should append admin
object to the user object.
good luck ✌