Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager Loading on Auth::user() in Laravel 5.2

I use the current authenticated user through the Auth::user() object on almost every single page. My users table has many polls.

Now every time I want to receive the related polls of my user Auth::user()->polls Laravel will perform a query to the database.

Is there a way to make - or a place to inject - the Auth::user() object Eager Loading the related polls and other related stuff?

like image 549
nipeco Avatar asked Jan 23 '26 09:01

nipeco


1 Answers

the Auth::user() function returns the same user object every time you use it. It does not go back to the database every time to get the user again.

So the first time you call Auth::user()->polls, it will query the database to get their polls. Then the rest of the times you call it, you are retrieving the polls from the object (the object keeps the polls data on its model). So this may not be a big issue as it only requires one database call to get the polls no matter how many times you use it.

To answer the question of how you would do this though: The Auth facade returns an object of class Illuminate\Auth\Guard. You would need to create a new class that extends that, then over-write the user() method to retrieve the user with the polls. You can check out that class to learn more about how it works, Taylor is very good about commenting the code and showing you what is going on so you can change if needed.

like image 142
Jeff Avatar answered Jan 25 '26 23:01

Jeff