Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if validation failed in laravel

I would like to know when a validation failed by using this kind of code writing (I'm using laravel 5.4)

$this->validate($request, [
    'name' => 'required|min:2|max:255'
]);

I know that I can use this:

$validator = Validator::make($request->all(), [
    'name' => 'required|min:2|max:255'
]);

if ($validator->fails()) { //Not okay }

But I would like to keep this way of validating by using $this->validate instead of using the Validator model.

So ... is it possible to use something like:

//This is not working btw

$test = $this->validate($request, [
    'name' => 'required|min:2|max:255'
]);

if( $test )
{ //Ok }
else
{ //Not okay };
like image 573
Atnaize Avatar asked Jan 16 '18 11:01

Atnaize


People also ask

How does a validator fail?

Validation errors typically occur when a request is malformed -- usually because a field has not been given the correct value type, or the JSON is misformatted.

What does validate return in laravel?

XHR Requests & Validation When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

How does laravel validation work?

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

What is validator in laravel?

Validation is the process of checking the incoming data. By default, laravel provides the base controller class that uses the ValidatesRequests trait to validate all the incoming Http requests.


1 Answers

You can use it like this:

$request->validate($rules);

or

$request->validate([
    'name' => 'required|min:2|max:255'
]);

Then it returns the errors.

$test = $request->validate([
           'name' => 'required|min:2|max:255'
        ]);

and you need to check if there are no errors and then you can do what ever you want.

In your case you need to do it like this:

$validator = Validator::make($request->all(), [
    'name' => 'required|min:2|max:255'
]);

if ($validator->fails()) {
    return view('view_name');
} else {
    return view('view_name');
}
like image 141
lewis4u Avatar answered Oct 17 '22 10:10

lewis4u