Table of contents

laravel remember me

In my previous post, I share how to implement custom expiration for your Laravel Remember Me authentication/login. But when I test my code it seems not to work if I delete the session and it will be redirected me to the login page. So I researched but still no luck then I check the Auth Session Guard and I found that there is a public method that can set the Remember me duration by minutes.

 

Here is the full code of my LoginController.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Display login page.
     * 
     * @return Renderable
     */
    public function show()
    {
        return view('auth.login');
    }

    /**
     * Handle account login request
     * 
     * @param LoginRequest $request
     * 
     * @return \Illuminate\Http\Response
     */
    public function login(LoginRequest $request)
    {
        $credentials = $request->getCredentials();

        if(!Auth::validate($credentials)):
            return redirect()->to('login')
                ->withErrors(trans('auth.failed'));
        endif;

        $user = Auth::getProvider()->retrieveByCredentials($credentials);

        if($request->get('remember')):
            Auth::setRememberDuration(43200); // equivalent to 1 month
        endif;

        Auth::login($user, $request->get('remember'));

        return $this->authenticated($request, $user);
    }

    /**
     * Handle response after user authenticated
     * 
     * @param Request $request
     * @param Auth $user
     * 
     * @return \Illuminate\Http\Response
     */
    protected function authenticated(Request $request, $user) 
    {
        return redirect()->intended();
    }
}

 

In my previous tutorial, I created a custom Trait Class that customizes the Laravel remember me authentication/login. But now I removed it and just put the 3 lines of code before Auth::login() method.

 

if($request->get('remember')):
   Auth::setRememberDuration(43200);
endif;

 

In just 3 lines you will now customize the Laravel remember me. I hope it helps. Thank you for reading :)