Home > Software engineering >  How to get error validation data in Custom Form Request
How to get error validation data in Custom Form Request

Time:01-18

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()

CodePudding user response:

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)

  • Related