Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lars-Janssen's avatar

Laravel api Auth::attempt not working

Hello,

When I try to check if a user can sign it like this:

if(Auth::attempt(array('email' => $request->email, 'password' => $request->password)))

It throws an error:

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\TokenGuard' does not have a method 'attempt'

When a user is signed in I want to send his/her api_token back.

Why is that? My default guard is token.

0 likes
9 replies
d3xt3r's avatar

Its exactly what it says, TokenGuard does not method called attempt ... what are you trying to do ???

Lars-Janssen's avatar

@premsaurav I'm trying to validate the user. And when he or she signed in successfully I want to send his token back.

d3xt3r's avatar

Token guard doesn't work that way,

  1. Authenticate the user, using session guard.
  2. On successful authentication, generate a token and save it against the user,
  3. On others routes where you need the token, use token guard.
Lars-Janssen's avatar

@premsaurav oke, so if my default is api and I want to use a session I should just put it in my web middleware route right? Like this:

Route::group(['prefix' => 'api/v1','middleware' => ['web']], function () {
    Route::post('/login', 'api\v1\EmployeeController@login');
});
d3xt3r's avatar
d3xt3r
Best Answer
Level 29

If its only about the Api's you dont need the web middleware, which is required if you want to login the user with session and cookies ...

public function login() {
    
    if(Auth::guard('web')->attempt(['email' => $email, 'password' => $password], false, false)) {
        // user credentials are correct. Issue a token and use it in next requests
        // Notice false, false => no login is performed
    } else {
        // invalid credentials, act accordingly
    }
}
2 likes
Lars-Janssen's avatar

@premsaurav how could I get a value of the authenticated user like that? Something like this?

Auth::guard('web')->FirstName
d3xt3r's avatar
public function login() {
    
    if(Auth::guard('web')->attempt(['email' => $email, 'password' => $password], false, false)) {
        
     $user = Auth::guard('web')->getLastAttempted(); // get hold of the user
    
    // user credentials are correct. Issue a token and use it in next requests
        // Notice false, false => no login is performed
    } else {
        // invalid credentials, act accordingly
    }
}
1 like
anAbhijeet's avatar

What is the ideal way to authenticate user using password and return token on successful authentication? Should I edit the TokenGuard, to add attempt() method?

Please or to participate in this conversation.