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 };
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.
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.
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.
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With