Laravel Validator Not Working Properly - Redirecting main page
Asked Answered
S

5

7

Laravel 5.5

public function register(Request $request) {
    request()->validate([
        'email' => 'required:email'
        'password' => 'required|min:6'
    ]);

    return response()->json(["message" => "Hello World"]); 
}

If validator is fails, not giving error messages. Redirecting main page.

Specialism answered 22/9, 2017 at 14:10 Comment(6)
shouldn't be $request->validate?Ovary
Same thing, I tried bothSpecialism
required:email should be required|emailForby
Still same, I should have made mistake when I simplify the codeSpecialism
@BugraDayi, I can assume you are using the web.php route instead of api.php route file?Endamoeba
@OmisakinOluwatobi , I am using api.phpSpecialism
T
24

If the code you're using redirects you to the previous page when validation fails, it means that you didn't tell the server what kind of response you want to receive.

Set a proper header to get JSON. It will make the validator send JSON in response. For example:

$.ajax({
  headers: {
    Accept : "application/json"
  },
  ...
});

Then this code will work as expected:

public function register(Request $request) 
{
    $request->validate([
        'email' => 'required:email'
        'password' => 'required|min:6'
    ]);

    return response()->json(["message" => "Hello World"]);
}
Turbosupercharger answered 22/9, 2017 at 15:2 Comment(1)
Thanks a lot, somebody said that. I should have written Content-type:application/json instead of Accept:application/json :(Specialism
S
8

I had the same problem when testing my rest api in Postman application.

  1. if we don't want to modify our current code of laravel redirect repose, we have to put Accept:-application/json and ContentType:-application/json

enter image description here

  1. For modifying code in controller class file, i did it like this and got the json response instead of redirecting to home page.

       public function register(Request $request)
       {
           $validator = Validator::make($request->all(), [
             'name' => 'required|string|max:255',
             'email' => 'required|string|email|max:255|unique:users',
             'password' => 'required|string|min:6',
             ]);
    
            if ($validator->fails()) {
               return response()->json($validator->errors());
             } else {
                // do something
            }
        }
    

before it looks like below codes it was redirecting to home page

This is validator function

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
    ]);
}

public function register(Request $request)
{
   
    // Here the request is validated. The validator method is located
    // inside the RegisterController, and makes sure the name, email
    // password and password_confirmation fields are required.
    $this->validator($request->all())->validate();

    // A Registered event is created and will trigger any relevant
    // observers, such as sending a confirmation email or any 
    // code that needs to be run as soon as the user is created.
    event(new Registered($user = $this->create($request->all())));

    // After the user is created, he's logged in.
    $this->guard()->login($user);

    // And finally this is the hook that we want. If there is no
    // registered() method or it returns null, redirect him to
    // some other URL. In our case, we just need to implement
    // that method to return the correct response.
    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}
Spaniard answered 8/11, 2017 at 9:58 Comment(1)
thank you when add accept to insomnia or postman its worked. and redirect stoppedFriesian
T
1

You can do this like this :

$validator = Validator::make($request->all(), [
    'email' => 'required|email', //use pipe here to apply multiple validations rules and add a ','
    'password' => 'required|min:6'
]);

if ($validator->fails()) {
    return response()->json(['errors' => $validator->errors()]);
}
return response()->json(["message" => "Hello World"]);
Teaser answered 22/9, 2017 at 14:17 Comment(8)
He is not using blade file to show errors, output is in response and JSON format.Ovary
Not solved, still redirecting main page and I am not using blades, I am building REST APISpecialism
This should work. Check out the documentation laravel.com/docs/5.5/… laravel.com/docs/5.5/validation#manually-creating-validatorsAstyanax
This code is working but this is old version of validation, I just want to figure out why new version is not workingSpecialism
Old version ? This is not, this is the current version!Teaser
link @TeaserSpecialism
This is a shortcut to write validation quickly with default behaviors. By using it, validation will automatically redirect to the previous pages with errors. But in the case you want to have a custom way to handle errors (like return them as JSON), this is totally legit : laravel.com/docs/5.5/validation#manually-creating-validatorsTeaser
But if you are creating an API, you may want to go with Lumen microframework from Laravel. Things are made to be simple as possible for building APIs : "The $this->validate helper which is available in Lumen will always return a JSON response with the relevant error messages". lumen.laravel.com/docs/5.5/validationTeaser
M
1

The validation is working well, but, $request->validate() will redirect you to the previous page. I recommend you to manually create your validations: Manually Creating Validations. You could do something like this:

use Illuminate\Http\Request;
use Validator;

class YourClass extends Controller{
    public function yourFunction(Request $request) {
        $validator = Validator::make($request->all(),[
            'field_1' => 'rule1|rule2',
            'field_2' => 'rule1|rule2'
        ]);
        
        if ($validator->fails()) {
            return response()->json($validator->errors());
        } else {
            /*Something else*/
        }
    }
}
Millett answered 22/9, 2017 at 14:34 Comment(3)
This code is working but this is old version of validation, I just want to figure out why new version is not workingSpecialism
What do you mean by old? It's Laravel 5.5 Docs. However, $request->validate() knows what to do depending on the request and, as mentioned before, will redirect automatically to the previous page, but, in this section: laravel.com/docs/5.5/validation#validation-quickstart, in the AJAX Request & Validation section, says that for AJAX request will generate a JSON response, maybe you have to set the "Accept" Header of the request to "application/json".Millett
Oh thank you so much, I should have written Content-type:application/json instead of Accept:application/json.Specialism
D
0

try this, hope this code can help you

$this->validate($request, [
        'email'    => 'required|email',
        'password' => 'required|min:6'
    ]);
Disproportionation answered 22/9, 2017 at 14:27 Comment(1)
Sorry I know this version of validation but still redirecting the main page not giving errorsSpecialism

© 2022 - 2024 — McMap. All rights reserved.