0

I'm studying Laravel 11 and I have my first problem using PHPStorm (I don't know if it's my test or not).

I have this controller:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class LoginController extends Controller
{
  public function login(Request $request)
  {
    $request->validate([
      'email' => 'email|string',
      'password' => 'required|min:8',
    ]);

    $credentials = request(['email', 'password']);

    if (!$token = auth()->attempt($credentials)) {
      return jsonResponse(status: 401, message: 'Unauthorized');
    }

    return jsonResponse(data: [
      'token'      => $token,
      'expires_in' => auth()->factory()->getTTL() * 60
    ]);
  }
}

My test code:

public function test_email_must_be_required(): void
  {
    $credentials = ['password' => 'password'];

    $response = $this->postJson("{$this->apiBase}/login", $credentials);

    $response->assertStatus(422);
    $response->assertJsonStructure(['message', 'data', 'status', 'errors' => ['email']]);
    $response->assertJsonFragment(['errors' => ['email' => ['The email field is required.']]]);
  }

But when I run the test, I have the following response:

enter image description here

However, it should not return 401 because the email in the test credentials is not being sent. It should return response code 422 instead.

[EDIT] When I change my validate method:

...
   'email' => 'required|email|string',
...

My code response is 200:

enter image description here

[EDIT 2]

This is my routes/api.php code:

enter image description here

2
  • 1
    Can you share the code for route /login in your route file (web/api) Commented Oct 6, 2024 at 4:59
  • @skdishansacin sure, I've edited my post to show you that code. Commented Oct 6, 2024 at 15:27

1 Answer 1

1
'email' => 'email|string',

This rule checks if the email is a valid email format and is a string. However, the field is not marked as required. Therefore, if no email is provided in the request, the validation will not fail, and the request will proceed to the next step (which is auth()->attempt()), where it eventually returns a 401 Unauthorized response due to missing credentials.

Sign up to request clarification or add additional context in comments.

1 Comment

Yesterday I've edited my post to add the "required" condition and the respose was 200.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.