How to get validation message in laravel 5.5 - php

hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)

In Laravel 5.5, like the documentation mention, the validation process is very easy :
Displaying The Validation Errors :
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error
messages to the view in our GET route. This is because Laravel will
check for errors in the session data, and automatically bind them to
the view if they are available.
AJAX Requests & Validation :
In this example, we used a traditional form to send data to the
application. However, many applications use AJAX requests. When using
the validate method during an AJAX 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.
So as you said : that means you don't need to put your ifs to handle validation laravel will take care of them itself great :)

here is some syntax that i use
public static $user_rule = array(
'user_id' => 'required',
'token' => 'required',
);
public static function user($data)
{
try{
$rules = User::$user_rule;
$validation = validator::make($data,$rules);
if($validation->passes())
{
}
else
{
return Response::json(array('success' => 0, 'msg'=> $validation->getMessageBag()->first()),200);
}
return 1;
}
catch(\Illuminate\Databas\QueryException $e) {
return Response::json(array('success' => 0, 'msg' => $e->getMessage()),200);
}
}
hope this will help you!

Please add Accept: application/json in you header.
Laravel automatically send an error message with response code.

As per 2019 Laravel 5.8 it is as easy as this:
// create the validator and make a validation here...
if ($validator->fails()) {
$fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}
You will get the array of arrays of the fields' names and error messages.

You can show first error.
if ($validator->fails()) {
$error = $validator->errors()->first();
}
For all error :
$validator->errors()

Related

Is there a way to override or change php/laravel request validate status code?

As you all may know, when we use laravel validate() function, the error status code it throws is 422. Is there a way to override or change the status code to 400?
$request->validate([ 'title' => 'required|unique:posts' ]);
With this code, when error occur, that status code it return is 422, and I want to change that to 400.
I have tried checking manually with if else, but I want to make use of the validate function because it's such a great feature.
You can use Validator for add custom code during validator fails.
For that you can try with this way:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts',
]);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors(),
], 400);
}

Laravel Validator. Unable to retrieve both errors and Input

I am using Laravel for a project and i am trying to validate some input fields from a form. I am using the Validator class.
Here is the code in my controller.
$validator = Validator::make($request->all(), [
'arithmos_kinhths' => 'required',
'kathgoria_kinhths' => ['required',Rule::notIn(['-'])],
'prohgoumenos_paroxos_kinhths' => ['required',Rule::notIn(['-'])],
'programma_kinhths' => ['required',Rule::notIn(['-'])],
'project_kinhths' => ['required',Rule::notIn(['-'])],
'kathogoria_epidothshs_kinhths' =>['required',Rule::notIn(['-'])],
'talk_to_eu_kinhths' => ['required',Rule::notIn(['-'])],
'pagio_kinhths' => 'required',
'sms_kinhths' => ['required',Rule::notIn(['-'])],
'internet_kinhths' => ['required',Rule::notIn(['-'])],
'international_kinhths' => ['required',Rule::notIn(['-'])],
'twin_sim_kinhths' => ['required',Rule::notIn(['-'])],
'wind_unlimited_kinhths' => ['required',Rule::notIn(['-'])],
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
In the blade file i am trying to catch the errors using the code bellow.
#if($errors->any())
#foreach($errors->all() as $error)
<script>
$.notify(
{
title: '<strong>ERROR!</strong>',
message: '{{$error}}',
},
{
type: 'danger',
},
)
</script>
#endforeach
#endif
Also i want to put the old values into the input fields using {{old('value'}}
The problem i have is that i can't combine both errors and inputs. If i return only the errors using withErrors($validator) the errors are printed out. And if i return only withInput i have the post values.
Any ideas?
withInputs()
try this, i hope that help a little , or
you can
return back()->with('errors',$validator)->withInputs()
you can use $this->validatorWith([]) then follow your code, you don't need to manually redirect back to that page. your request will auto redirect to that page from where request has happened. this function belongs to trait Illuminate/Foundation/Validation/ValidatesRequests which is use by app\Http\Controllers\Controller.php. you just need to use. for more about this trait see here ValidateRequest
$this->validatorWith([
'request_param' => 'required',
]);

Handle validator to return json

Laravel throw an exception at $validator->fails() call.
Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.
I used the Validator facade to check the sent data.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
But, when I use xdebug, I see something strange. The fails methods seems throw an exception.
Laravel send an error HTML page with title:
Validation rule unique requires at least 1 parameters.
The route is used in api.php
Route::post('register', 'Api\UserController#register');
Do you have an explanation for this?
Thx for reading.
The syntax for unique rule is unique:table,column,except,idColumn.
So i changed it for you to use the users table.
If you don't want to use the users table change the users part behind unique:
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique
In your API request add the following header:
...
Accept: application/json // <-----
This will tell Laravel that you want a response in a json format.
Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.

Add a validation which is not related to the form

I want to add a validation on a form. My actual form works, here it is:
public function store(Request $request, $id)
{
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
]);
// Do something if everything is OK.
}
Now, I want to check if the user is "active" too. So something like:
\Auth::user()->isActive();
And return an error with the other validation errors if the user is not active.
Can I append something to the validator that has no relation with the form itself? I mean I want to add an error to the other errors if the user is not active.
That code is only validating the request variable (first argument of validate() function). So you will have to put someting in the request to validate it. It applies the rules to the object/array given.
$request->is_active = Auth::user()->isActive();
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
'is_active' => true //or whatever rule you want
]);
Anyways, I never tried that so not sure it will work. The usual way is to do an if
if ( !Auth::user()->isActive() ) {
return redirect->back()->withErrors(['account' => 'Your account is not active, please activate it']);
}
//continue here

Laravel 5.2 - Validation with API

I am using Laravel 5.2 for validation with a REST JSON API.
I have a UserController that extends Controller and uses the ValidatesRequests trait.
Sample code:
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id',
]);
This throws an exception, so in my Exceptions/Handler.php I have this code:
public function render($request, Exception $e)
{
return response()->json([
'responseCode' => 1,
'responseTxt' => $e->getMessage(),
], 400);
}
However, when validating responseTxt is always:
Array
(
[responseCode] => 1
[responseTxt] => The given data failed to pass validation.
)
I have used Laravel 4.2 in the past and remember the validation errors providing more detail about what failed to validate.
How can I know which field failed validation and why?
A ValidationException gets thrown which gets rendered as a single generic message if the request wants JSON.
Instead of using the validate() method, manually invoke the validator, e.g.:
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id',
]);
if ($validator->fails()) {
return new JsonResponse(['errors' => $validator->messages()], 422);
}
https://laravel.com/docs/5.2/validation#manually-creating-validators
As an aside, I'd recommend a 422 HTTP status code rather than a 400. A 400 usually implies malformed syntax. Something that causes a validation error usually means that the syntax was correct, but the data was not valid. 422 means "Unprocessable Entity"
https://www.rfc-editor.org/rfc/rfc4918#section-11.2
In Laravel 5.2 validate() method throws a Illuminate\Validation\ValidationException, so if you want to get the response use getResponse() instead getMessage().
For example, an easy way to handle this exception could be doing something like this:
try{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id'
]);
}catch( \Illuminate\Validation\ValidationException $e ){
return $e->getResponse();
}

Categories