3

I have created a custom request form for login validation, It works fine if I put email and password field that's what I set for rules, email and password is required, but the problem is, I can't use the errors data,

    /**
     * Signin Controller
     *
     * @param \App\Http\Requests\Auth\Signin $request
     */
    public function signin(Signin $request)
    {
        if ($request->validated()) {
            return response()->json(['hello' => 'hi']);
        } else {
            return response()->json(['error' => $request->errors()]);
        }
    }

This is the Request form

<?php

namespace App\Http\Requests\Auth;

use Illuminate\Foundation\Http\FormRequest;

class Signin extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function messages()
    {
        return [
            'email.required' => 'Email field is required.'
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'email' => 'required',
            'password' => 'required'
        ];
    }
}

Now when I try to make a post request to the signin controller, if email and password included then its return a json response, but if I only use email or password then it response a 405 method not allowed I'm expecting a json response with error data like errors()

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Just to confirm, have you cleared your route cache and others with `php artisan optimize:clear`? Also can you check your route list with `php artisan route:list`? You can also try changing your route sorting. Usually the problem can be the sequence of the routes declaration. – cengsemihsahin Jan 17 '23 at 00:01
  • Also can you create an error message to test its output with `ValidationException::withMessages()` and check if you get it? – cengsemihsahin Jan 17 '23 at 00:04
  • Hi @cengsemihsahin, Thanks for response. I can see my route is available on route:list. I think it might not a route issue. When I use email and password field I get 200 response. But when I use {email: "test@gmail.com"} not {email: "...", password: "..."} then I get 405 method not allowed, in both case I tried with post method. check this Route::post('/signin', [AuthController::class, 'signin']); – Sakib Hasan Jan 17 '23 at 00:13
  • May be try restart your webserver. Might fix the issue. Give a shot :) – cengsemihsahin Jan 17 '23 at 00:28
  • FormRequests throw an exception when the validation fails ... so your `if` statement isn't even running as you are not even getting into the Controller method when validation fails (Form Requests are validated when they are resolved) ... you would have to deal with the exception in your Exception Handler – lagbox Jan 17 '23 at 00:33
  • @lagbox could you please show me an example? that will be great thanks – Sakib Hasan Jan 17 '23 at 00:51
  • and why its giving me a MethodNotAllowedHttpException exception instead of validationexception? – Sakib Hasan Jan 17 '23 at 01:01
  • Your 405 response indicate that method is not allowed probably because the lack of validation is redirecting to the previous location but in this case with the get verb and probably that method is not allowed in your routes. Could it be? https://laravel.com/docs/9.x/validation#form-request-validation:~:text=If%20validation%20fails%2C%20a,the%20validation%20errors. – Manuel Glez Jan 17 '23 at 01:13

1 Answers1

2

As I understood, failedValidation would help you

use Illuminate\Http\JsonResponse;

class Signin extends FormRequest
{
    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json($validator->errors(), JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
    }
}

This return the JSON object with 422 error(default error code for validation)

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • if they pass the correct header to receive JSON the Exception Handler should return JSON for a `ValidationException` – lagbox Jan 18 '23 at 00:28