Home > OS >  laravel Form request validation return 404 error
laravel Form request validation return 404 error

Time:08-20

i'm new to laravel , hope someone could help me with this problem ,

i've created a request class to validate my inputs . But when the validation fails it doesn't return any error messages instead showing a 404 error.

my request class , recoverIdRequest

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class recoverIdRequest 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
     */
    public function rules()
    {
        return [
            'dob' => 'required',
            'email' => 'required',
        ];
    }
}

and here's my controller : testController

class testController extends Controller
{
/** 
*
* @param  \App\Http\Requests\recoverIdRequest $request
* @return Illuminate\Http\Response
*/
    public function test(recoverIdRequest $request)
    {
       
      $validated = $request->validated();
    
      
        $dob = $request->input('dob');
        $new_dob = Carbon::parse($dob)->format('Y-m-d');
        $email = $request->input('email');
        $exist =Appl_students::where('email', $email)
            ->whereBetween('dob', [$new_dob, $new_dob])
            ->select('id', 'first_name')
            ->first();
        if ($exist == null) {
            return response()->json(['data' => $exist, 'success' => false, 'message' => "User not found"]);
        } else {
            $date_of_birth = Carbon::parse($dob)->format('d-m-Y');
            $institute =Master::select(
              'institution_name', 'website_url', 'institution_place', 
              'institution_post', 'institution_district', 'institution_pin', 
              'institution_state', 'institution_phone', 'institution_email')
              ->first();
                return $institute;
 Mail::to($email)->send(new RecoverApplicationId($exist->id, $date_of_birth, $exist->first_name, $institute->institution_name));
            return response()->json(['data' => $exist, 'success' => true, 'message' => "Application ID has seen sent to registered mail"]);
        }
    }
      
}

and this is the response in postman when the validation fails :

and this is the response in postman when the validation fails :

routes/api.php

Route::group([ 'prefix'=>'modelTesting', ], function() {
    Route::post('test/{id}' [testController::class,'test'])->middleware(['auth:api', 'scope:admin']);
}); 

CodePudding user response:

You should follow the naming convention first in all your classes.

As the information not very much clear but it should return 422 error status. It might be the problem that when validation is failed then it is trying to redirect none existence URL. Please check the type of method you are using in postman to call the api. If it not resolved please paste the request data from the postman. And the routes.php

CodePudding user response:

It does not give 404, if the validation process is not successful, validation redirects back to the previous page, in your case it gives 404 because there is no rest API and a previous page ... let's agree here it's very natural and you just have to write a small validation method for it

try it, add this method to your form request class(recoverIdRequest) and try again


    /**
     * Returns validations errors.
     *
     * @param Validator $validator
     * @throws  HttpResponseException
     */
    protected function failedValidation(Validator $validator)
    {
        // you can debug with dd() in this method 
        if ($this->wantsJson() || $this->ajax()) {
            throw new HttpResponseException(response()->json($validator->errors(), 422));
        }
        parent::failedValidation($validator);
    }


second step you should change handler

app/exceptions/Handler.php


public function render($request, Exception $e)
{
    if ($request->ajax() || $request->wantsJson())
    {
        $json = [
            'success' => false,
            'error' => [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
            ],
        ];

        return response()->json($json, 400);
    }

    return parent::render($request, $e);
}

CodePudding user response:

Resolved

it was a problem with postman headers,i was able to fix the issue using the following headers :

Accept: application/json
X-Requested-With: XMLHttpRequest
  • Related