How to custom response JSON object validator - laravel

i have problem with response validator like this :
{
"email": [
"The email field is required."
],
"password": [
"The password field is required."
]
}
im want to like this :
{
"email":
"The email field is required."
,
"password":
"The password field is required."
}
this my validator
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
everyone can help me ? thanks very much

Related

Laravel validator custom messages doesn't work with nested attributes

I try to perform a manual validation according to the documentation.
There is my rules:
$rules = [
"firstname" => ['required'],
"coord.address" => ['required'],
];
And there is my custom messages:
$messages = [
"firstname.required" => "Custom message for firstname",
"coord.address.required" => "Custom message for address",
];
My call for perform the validation
$errorMessages = Validator::make($attributes, $rules, $messages)->errors()->messages();
And there is my messages form the validator:
[
"firstname" => "Custom message for firstname",
"coord.address" => "The field coord.address is required",
]
What im doing wrong ?
I tried to use an array of messages like this:
$messages = [
"coord" => [
"address.required" => "Custom message",
]
];
Or like this:
$messages = [
"coord" => [
"address" => [
"required" => "Custom message"
]
]
];
But same problem.

L8 - API - Form Request on optional input JSON object

I'm working on Form Request and I've a question about how to use it with optional input object.
My API get a simple input JSON like:
{
"user": [
{
"name": "Valentino",
"car": {
"model": "ferrari",
"color": {
"front": "red",
"back": "black"
}
}
},
"name": "Stefano",
"car": {
"model": "mercedes"
}
}
]
}
the Controller:
public function insertUser(StoreUserRequest $request) {
}
the For Request Validation Class:
public function rules()
{
return [
'user' => 'required|array',
'user.*.name' => 'string|required',
'user.*.car' => 'required|array',
'user.*.car.model' => 'required|string',
'user.*.car.color' => 'nullable|array', // could be present or not
'user.*.car.color.front' => 'required|string', // should be validated only if exists 'color'
'user.*.car.color.back' => 'required|string', // should be validated only if exists 'color'
];
}
the color object could be optional into the input JSON; how I can set StoreUserRequest.php class to validate the color object only if exists?
Thank you very much!
#Tippin tell me a solution using required_with rule:
public function rules()
{
return [
'user' => 'required|array',
'user.*.name' => 'string|required',
'user.*.car' => 'required|array',
'user.*.car.model' => 'required|string',
'user.*.car.color' => 'nullable|array', // could be present or not
'user.*.car.color.front' => 'required_with:user.*.car.color|string',
'user.*.car.color.back' => 'required_with:user.*.car.color|string',
];
}
Thanks

Laravel 5.8 ManyToMany relationship child relation usign foreign key doesn't work

When I call my image resource it returns the correct data from my model:
Image resource:
return [
'id' => $this->id,
'name' => $this->name,
'presentation' => $this->presentation->description,
'slug' =>$this->filename
];
Image Model:
public function presentation()
{
return $this->hasOne(ProductPresentation::class, 'id', 'presentation_id');
}
Returns:
{
"data": [
{
"id": 1,
"name": "White Gold",
"presentation": "Product x",
"slug": "products/white-gold.jpg"
}
}
But when I call the manyToMany (Products -> images) relation I only get the the Id not the foreign relation
"data": [
{
"id": 1,
"name": "White Gold",
"price": "€ 10,00",
"images": [
{
"id": 1,
"name": "White Gold",
"filename": "products/white-gold.jpg",
"presentation_id": 1
}
]
},
The Products resource calls the image resource but this doesn't load the relation ( need "presentation": "Product x" instead of "presentation_id": 1)
Using resource:
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->formattedPrice,
'images' => $this->images
];
using model:
public function images()
{
return $this->belongsToMany(Image::class);
}
So the question would be how do I add the relation to belongsToMany(Image::class)
Try to change
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->formattedPrice,
'images' => $this->images
];
To
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->formattedPrice,
'images' => YourImageResource::collection($this->images)
];

How to write validation rule for JSON laravel?

There is JSON object that I want to validate:
[{
"id": 1,
"settings": {
"GRSYSEM": 1
}
},
{
"id": 2,
"settings": {
"GRSYSEM": 1
}
},
{
"id": 3,
"settings": {
"GRSYSEM": 1
}
}
]
How to write validation rule in Laravel?
I tried this rule:
$validator = Validator::make($request->all(), [
'id' => 'required|array',
'id.*' => 'required',
'settings.*.GRSYSEM' => 'required'
]);
You are almost there, simply put the wildcard * first:
$validator = Validator::make($request->all(), [
'*.id' => 'required',
'*.settings.GRSYSEM' => 'required'
]);
It literally says: For each element in the array, I expect an id and a setting GRSYSEM.
You could also ensure it's an array by using a little hack:
$data = ['input' => $request->all()];
$validator = Validator::make($data, [
'input' => 'required|array',
'input.*.id' => 'required',
'input.*.settings.GRSYSEM' => 'required'
]);
If entry in $request->all() is id (as I can see), you should try like that :
$validator = Validator::make($request->all(), [
'id' => 'required|array',
'id.*.id' => 'required',
'id.*.settings.GRSYSEM' => 'required'
]);

Format validation error message as nested associative array

I have a Json object of data as shown below
{
"name": "something",
"location": {
"city": "some where",
"country": "some where",
}
}
Rule used to validate Request is
[
'name' => 'required',
'location.city' => 'required',
'location.country' => 'required'
]
Which returns error message like
{
"name": [
"The name field is required."
],
"location.city": [
"The location.city field is required."
],
"location.county": [
"The location.country field is required."
]
}
How can I format error message as a nested array like the Request.
{
"name": [
"The name field is required."
],
"location": {
"city": [
"The city field is required"
],
"country": [
"The country field is required"
]
}
}
Any default methods available ?
I am using Illuminate\Foundation\Http\FormRequest
In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.
$validator = Validator::make($request->all(), [
'name' => 'required',
'location.city' => 'required',
'location.country' => 'required'
]);
if ($validator->fails()) {
return response()->json($yourOwnFormat,422);
//you can use $validator->errors() to build it
}
For those who looking for the solution This is how I implemented
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class UserStoreRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required',
'location.city' => 'required'
'location.country' => 'required'
];
}
public function attributes()
{
return [
'location.city' => 'City'
'location.country' => 'Country'
];
}
protected function failedValidation(Validator $validator)
{
$errors = $validator->errors()->getMessages();
$errors_formated = array();
foreach ($errors as $key => $value) {
array_set($errors_formated, $key, $value);
}
throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
}
}
The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name
Is it? Laravel Documentation- Customizing the Error Messages
public function messages()
{
return [
'location.city' => 'The city field is required',
'location.county' => 'The county field is required',
];
}

Resources