ssquare's avatar

Failing Laravel Login Test

I am using fortify but trying to customize the login by using sanctum. My login code looks like:

FortifyServiceProvider.php

        Fortify::authenticateUsing(function (Request $request) {
            $request->validate([
                'email' => 'required|email',
                'password' => 'required',
                'device_name' => 'required',
            ]);
            $user = User::where('email', $request->email)->first();
            if (! $user || ! Hash::check($request->password, $user->password)) {
                throw ValidationException::withMessages([
                    'email' => ['The provided credentials are incorrect.'],
                ]);
            }
            $token = $user->createToken($request->device_name)->plainTextToken;
            return response()->json([
                'user' => new UserResource($user)
            ],200)
            ->header('x-auth-token', $token);
        });

And here is my test case:

    public function test_login_true()
    {
        $this->withoutExceptionHandling();
        $user = User::factory()->create();
        $credential = [
            'email' => $user->email,
            'password' => 'password',
            'device_name' => 'postman'
        ];
        $response = $this->json('post','/api/login',$credential);
        $response->assertRedirect('/home');
    }

and currently the error is showing:

TypeError: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\Http\JsonResponse given, called in /var/www/clinic/vendor/laravel/fortify/src/Actions/AttemptToAuthenticate.php on line 80

0 likes
3 replies
tykus's avatar

The Closure should return the User instance, not a Response.

ssquare's avatar

don't get it could you be little more specific? You mean it should return as

$token = $user->createToken($request->device_name)->plainTextToken;
return new UserResource($user);

Please or to participate in this conversation.