0

A user can belong to many clubs, so when they login I want to get that relationship and cache it in Auth::user() so that I can check it throughout the app and not have to hit the database each time.

I've been researching this but can't really find any info. The closest I came was a suggestion to add a custom authenticated() method to Http\Controllers\Auth\AuthController. I did, but it's not giving me anything.

protected function authenticated(Request $request, $user)
{
    $user->load('memberships');
}

Can somebody give me some pointers on how to resolve this?

2 Answers 2

1

A very simple way would be to listen for the 'Illuminate\Auth\Events\Login' event and when it fires, check to see if the clubs are in the session. If they are not, query the database for them and get them added to the session, and then return them from the session.

While they are technically not attached to the User model which would be returned by Auth::user(), the effect is the same, you'd just grab them from the session via session('clubs').

It technically doesn't make sense to say you want to cache something onto the model and storing it in the cache isn't something you'd really want to do anyway because the cache is the same among all users so the session would be the correct place to put it.

Sign up to request clarification or add additional context in comments.

1 Comment

Funny, I was originally looking at Events and dismissed it in favor of Auth. Your suggestion was simple and elegant and worked like a charm. Thanks!
0

Solution: Overriding postLogin() in AuthenticatesUsers trait so you're free to handle login

- In App\Http\Controllers\Auth\AuthController

public function postCustomLogin(Request $request){
    $this->validateLogin($request);

    $throttles = $this->isUsingThrottlesLoginsTrait();

    if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    $credentials = $this->getCredentials($request);

    if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {

        // DO SOME STUFF HERE. I FIRE AN event()
        event(new EventUserPlaylistChange());

        return $this->handleUserWasAuthenticated($request, $throttles);
    }

    if ($throttles && ! $lockedOut) {
        $this->incrementLoginAttempts($request);
    }

    return $this->sendFailedLoginResponse($request);
}

- In routes. Override postLogin route

Route::auth();
Route::post('login', 'Auth\AuthController@postCustomLogin');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.