Support the ongoing development of Laravel.io →
Authentication Cache
Last updated 2 years ago.
0
$user = Cache::remember('user', 60, function() {
    return Auth::user();
});

http://laravel.com/docs/cache#cache-usage

Last updated 2 years ago.
0

@zenry, that will cache the same user object for everyone, so I wouldn't do that..

Last updated 2 years ago.
0

I am not sure if this is the best method of doing so but on my base controller __construct method I set $this->user to equal Auth::user(); so I know if a user is logged in and it acts as a "cache" for every time I need to check a users details during that session.

I guess if all your doing is displaying the username then you could use a session to do so.

Last updated 2 years ago.
0

Saving the username to a session won't matter. It looks like Laravel will always run the query against the user as long as they are logged in. So pulling the username from Auth::user() doesn't require any extra queries.

Last updated 2 years ago.
0

Any way extend Auth for cache ?

Last updated 2 years ago.
0

It's one very simple query and you shouldn't be bothering caching this because it's the lowest performance impact query on each request.

Focus on solving the problems, instead.

Last updated 2 years ago.
0

The best way I found to implement this is to leverage the session.

if (Auth::attempt(array('email_address'=>Input::get('email_address'), 'password'=>Input::get('password'), 'active' => 1)))        {
        // Grab Authenticated User's Data Once
        $user_data = Auth::user();

        Session::put('user_id', $user_data->id);    
        Session::put('first_name', $user_data->first_name);
        Session::put('last_name', $user_data->last_name);
        Session::put('email_address', $user_data->email_address);

        return Redirect::intended('user/dashboard');
    } 
    else {
    	return Redirect::to('user/login')
            ->with('message', 'That username and password combination is invalid!')
            ->withInput();
    }

Then within the app, I simply need to grab that data from the users session. Very lightweight.

Hope that helps!

Last updated 2 years ago.
0

To cache the request everywhere without modifying existing code create a new auth driver that wraps the eloquent driver. See extending authentication.

Steps:

  1. Create a CachedUserProvider that implements UserProviderInterface

  2. The new provider is a decorator for the eloquentUserProvider. Each method will cache the call to the eloquentUserProvider. E.g.

public function retrieveById($identifier) {
  return $this->cache->remember(__METHOD__.$identifier, 60, function() {
    return $this->eloquentUserProvider->retrieveBy();
});
}
  1. Register new auth driver and register it in config
Auth::extend('cachedEloquent', function($app)
{
    return app->make('namespace\auth\CachedEloquentUserProvider');
});
  1. Update config to use new driver
//app/config/auth.php
return array(
  'driver' => 'cachedEloquent'
//...
);

Last updated 2 years ago.
0

When you are using an application that requires the user to be logged in, every single request already grabs the user from the database because of the auth filter.

So running Auth::user() doesn't do any extra queries and grabbing attributes such as Auth::user->name doesn't add any noticeable overhead.

Last updated 2 years ago.
0

You guys are right on both accounts. Every situation is different, and it all depends on the applications requirements to help determine the best method.

In effort to lighten things, and stop Auth from querying the users data on every request I simply modified the auth filter to check for the existence of a session variable, as it is a requirement for the logged in user experience.

Route::filter('auth', function()
{
    if( ! Session::get('user_id')){
        return Redirect::guest('user/login');		
    } 
});

This has effectively stopped the query on each request, and hasn't hampered any other features of Auth that I've discovered thus far.

Last updated 2 years ago.
0

Please damienadermann, could you possible provide a more complete example? I have spent whole evening trying to make it work, but without the success (on L4.2)

Here is my solution - it is probably bad, but works.

Last updated 2 years ago.
0

delmadord said:

Please damienadermann, could you possible provide a more complete example? I have spent whole evening trying to make it work, but without the success (on L4.2)

Here is my solution - it is probably bad, but works.

I copied your application structure and came up with this. I actually haven't tested it so their might be a few typos but the overall concept is there.

The key difference is all the eloquent work is done for you in the EloquentUserProvider so just utilize that. This is also easier to unit test and follows the Single Responsibility Principle. It also allows your to switch in any other provider you want to be cached.

Last updated 2 years ago.
0

Thanks damienadermann, I will take deeper look at it and post a result.

Last updated 2 years ago.
0

A solution that works for me http://laravel.io/bin/6z0bj

Last updated 2 years ago.
0

@maxbanton thank you very much :D

Last updated 2 years ago.
0

damienadermann said:

To cache the request everywhere without modifying existing code create a new auth driver that wraps the eloquent driver. See extending authentication.

Steps:

  1. Create a CachedUserProvider that implements UserProviderInterface

  2. The new provider is a decorator for the eloquentUserProvider. Each method will cache the call to the eloquentUserProvider. E.g.

public function retrieveById($identifier) {
 return $this->cache->remember(__METHOD__.$identifier, 60, function() {
   return $this->eloquentUserProvider->retrieveBy();
});
}
  1. Register new auth driver and register it in config
Auth::extend('cachedEloquent', function($app)
{
   return app->make('namespace\auth\CachedEloquentUserProvider');
});
  1. Update config to use new driver
//app/config/auth.php
return array(
 'driver' => 'cachedEloquent'
//...
);

@damienadermann 's suggestion works fine.

0

maxbanton said:

A solution that works for me http://laravel.io/bin/6z0bj

Hello, i'd like use your solution in laravel5, how to make it?

Last updated 9 years ago.
0

nullproduction said:

maxbanton said:

A solution that works for me http://laravel.io/bin/6z0bj

Hello, i'd like use your solution in laravel5, how to make it?

I corrected that for Laravel 5 - https://gist.github.com/nullproduction/eb30d2d9f3206931578c I think it will be useful for others artisans :)

Last updated 9 years ago.
0

The snippets for the Laravel 4 solution of @damienadermann are gone. Someone still has it ?

0

I am using this solution but for laravel 5.2 CreatesUserProviders.php needs to be changed (another case added to one method + one method added). Is there any way to extend CreatesUserProviders so to avoid changing vendor class (trait in this case)?

0

nullproduction said:

nullproduction said:

maxbanton said:

A solution that works for me http://laravel.io/bin/6z0bj

Hello, i'd like use your solution in laravel5, how to make it?

I corrected that for Laravel 5 - (snip)
I think it will be useful for others artisans :)

very nice, but it does not work in 5.3.
I packaged for Laravel 5.3.
[new] When model updated, cache clear and load (means reload).

see readme.
https://packagist.org/packages/hobbiot/cacheable-auth-user

0

Sign in to participate in this thread!

Eventy

Your banner here too?

modbase modbase Joined 31 Jan 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.