Auth::attempt() automatically stores the userid in session. https://github.com/illuminate/auth/blob/master/Guard.php#L358
and Auth::user() checks session before making a db call: https://github.com/illuminate/auth/blob/master/Guard.php#L115
So, you are already covered :-)
Ok
But if you need access every time to user property, like Auth::user()->profile
its better:
Session::put('userr', Auth::user());
and every time you need to access to user to use:
Session::get('user')->profile;
or use
Auth::user()->profile
every time.
I have found that every time you call Auth::user()->profile you do a query to database, maybe using session, performance improvements.
thanks!
I would personally not put the user in the session, because every time the user's data updates, you'll have to either update the session at that point, or add some complex logic to detect if the session data is out of date, and fetch the new data.
For example, lets say your user can leave comments in a forum. Each time they do, it increments their post count in the database. Well if their data is saved in the session, it will be out of date, unless you take the time to make sure it gets updated when they leave a comment.
Further, if you're saving session data in a database, you'll be hitting the database anyway.
I think it's fine to grab the user data directly from the database on every request. If the user object is particularly heavy with lots of child objects that need to be eagerly loaded for one reason or the other, then yes, I would then "cache" the user object in the session, and make sure it expires every ~15 minutes or so such that it's reasonably fresh.
But if your application is structured such that each page request requires all of that data from different sources, combined under your user object, I would probably re-think your database structure and/or your app's design to see if there is ways to make it more efficient.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community