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

afoysal's avatar

Return token in API authentication.

I am using Passport for API authentication. My API login function is like below.

public function apilogin (Request $request) {
        if( $request->is('api/*')){
            $validator = Validator::make($request->all(), [
                'email' => 'required|string|email|max:255',
                'password' => 'required|string|min:6',
            ]);
            if ($validator->fails())
            {
                return response(['errors'=>$validator->errors()->all()], 422);
            }
            $user = User::where('email', $request->email)->first();
            if ($user) {
                if (Hash::check($request->password, $user->password)) {
                    $token = $user->createToken('Laravel Password Grant Client')->accessToken;
                    $response = ['token' => $token, "message" => "successful"];
                    return response($response, 200);
                } else {
                    $response = ["message" => "Password mismatch"];
                    return response($response, 422);
                }
            } else {
                $response = ["message" =>'User does not exist'];
                return response($response, 422);
            }
        } 
    }

But I am not getting the token. My output is like below.

error

How can I get token as output ?

0 likes
2 replies
LaryAI's avatar
Level 58

The code seems to be correct. The issue might be with the request headers. Make sure that you are sending the request with the Accept header set to "application/json". If that doesn't work, try adding the following line to your config/app.php file under the providers array:

Laravel\Passport\PassportServiceProvider::class,

If the issue still persists, try clearing the cache by running the following command:

php artisan cache:clear

If none of the above solutions work, try using Postman to test the API and see if you get the token as output.

1 like

Please or to participate in this conversation.