Handle validator to return json - php

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.

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);
}

how to change the key of validation error in laravel

I am new to laravel and working on apis, I have made an api in which i have implemented validation.Everything is working fine but i am stuck on a little thing. I want to to change the key name in the validation error. For example For the "unique" validation error. This is what now showing
I want to rename "email"(text) key with "message"(text)
I have tried so many thing in illuminate/support/validation.php
messagebag.php file but if it changes then error show of "data undefined".
The links i followed are
https://stillat.com/blog/2018/04/21/laravel-5-message-bags-adding-messages-to-the-message-bag-with-add
https://laracasts.com/discuss/channels/laravel/custom-validation-message-for-array-using-different-key?page=0
Override laravel validation message
This is the validation code
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
You can manually loop over the error MessageBag and construct the response to replace a key
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
$errors = [];
foreach ($validator->errors()->messages() as $key => $value) {
if($key == 'email')
$key = 'message';
$errors[$key] = is_array($value) ? implode(',', $value) : $value;
//implode is for when you have multiple errors for a same key
//like email should valid as well as unique
}
$result = array("status" => count($errors)?0:1, 'data'=>$errors);
return $result;
In resources - lang - en (Or Any Langauge) - validation.php
Put This code in bottom:
'attributes' => [
'email' => 'The Email',
],
In order to change the key of the error message of a certain field, you can transfer the validation of this particular field from the request to the controller (or service). This way you can throw an error with any name you want.
For example:
if (#your validation of the field failed#) {
throw ValidationException::withMessages(['your_key' => 'your message']);
}
And don't forget this line:
use Illuminate\Validation\ValidationException;
The error now will look like this:
{
"message": "The given data was invalid.",
"errors": {
"your_key": [
"your message"
]
}
}
if I understand the problem well. This will help you:
a https://laravel.com/docs/7.x/validation#rule-unique
In your case:
'email' => 'required|email|unique:users,message'
unique:table,column,except,idColumn
Hope it helps.
In Laravel, you can try and validate your email this way:
'email'=>'required|email'

How to get validation message in laravel 5.5

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()

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