Laravel throws 404 when $request->validate fails

Viewed 3038

We're creating a REST API for our application.

web.php

Route::post('add-new-student', 'StudentController@addNewStudent');

StudentController.php

...
function addNewStudent(Request $request)
{
    $validation = $request->validate([
        'student_mobile' => 'required|digits:10',
        'student_name' => 'required|min:3|max:50',
        'student_email' => 'email:rfc|max:50',
    ]);

    if ($validation->fails()) {
        // show error json
    } else {
        // add new student
    }
}
...

Now when we send the JSON response, if there is error, instead of going to else block it shows 404 page in postman.

We don't know what we are doing wrong!

Note

  • Our routes are correct (double checked)
  • In postman, we are sending post request
2 Answers

The Validation Request class checks if your request is an ajax request or a normal request.

If it's a normal request it does: redirect()->back() with the validation messages in the session.

If it's an ajax request it shows a json object with the validation messages in it.

Frontend frameworks/libraries like example jQuery add a header to an ajax request to let the backend know it's an ajax request. Laravel checks this header to decide what to do.

Postman does not automatically send this header. So you should add one of the following headers manually:

Accept: application/json

X-Requested-With: XMLHttpRequest

The $request->validate() performs a redirect when it fails, then the if($validation->fails()) is never executed.

Correct answer is Manually Creating Validators

use Illuminate\Support\Facades\Validator; // include this at top

$validation = Validator::make($request->all() ,[
   'student_mobile'   =>  'required|digits:10',
   'student_name'     =>  'required|min:3|max:50',
   'student_email'    =>  'email:rfc|max:50',
]);

if($validation->fails()) {
   // validation failed
} else {
   // validation passed
}
Related