Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "login" and "attempt" method in Auth

I'm learning Laravel 5.4 and customizing and making my original Auth functionalities.

The below is my "authenticate" method.

public function authenticate(Request $request)
{
    $remember_me = (Input::has('remember')) ? true : false;
    Auth::guard('web');
    $this->validateLogin($request);
    $credentials = array(
        'username' => trim($request->input('username')),
        'password' => trim($request->input('password'))
    );
    if(Auth::attempt($credentials, $remember_me)){
        $user = Auth::guard('web')->user();
        Auth::guard('web')->login($user, $remember_me);
        return redirect()->route('mypage');
    }
    return redirect()->back();
}

I have a question about the part of $remember_me argument about both attempt and login methods noted above.

What is the difference between them?

When I saw the documentation, it said similar to, if you want to make "remember me" token, you can set the second boolean argument about both of them.

like image 889
t-pro Avatar asked Dec 19 '22 06:12

t-pro


1 Answers

attempt($credentials, $remember_me) will attempt to log the user in if the login credentials are correct. If they are not, then the user is not logged in. This method returns a boolean so you can check success.

login($user_id, $remember_me) will log the user in, without checking any credentials.

The remember me specifys if the user login should persist across browser sessions without needing to re-auth.

In your example I see your calling login(...) within your attempt(...). This shouldn't be needed. You can remove the login(...) line.

Example:

if(Auth::attempt($credentials, $remember_me)){
    return redirect()->route('mypage');
}
like image 110
Jono20201 Avatar answered Dec 20 '22 19:12

Jono20201