I have a contact form, with some field and i want to get error message based on the form field, i.e the error message for name, email, phone, subject and message
Here is what I get here:
XHRPOSThttp://127.0.0.1:8000/save
[HTTP/1.1 200 OK 137ms]
success false
errors [ "The name field is required.", "The email field is required.", "The phone field is required.", "The subject field is required.", "The description field is required." ]
because of this line in controller
$validator->errors()->all()
but I want the error message to be like:
errors:object{name:""The name field is required."
email:"The email field is required.", ...}
the controllers look like
$validator = Validator::make($request->all(), [
'name' => 'required|max:60',
'email' => 'required|email',
'phone' => 'required|min:10|numeric',
'subject' => 'required|max:100',
'description' => 'required|max:250',
]);
if ($validator->fails()) {
return response()->json([
'success' => false, 'errors' =>$validator->errors()->all()
]);
}
CodePudding user response:
You probably want to use the default Laravel validation function (available in all controllers), which handles this output automatically:
// SomeController.php
$this->validate($request, [
'name' => 'required|max:60',
// ...
]);
When the validation fails, a ValidationException
is thrown which should be automatically handled in your exception handler.
CodePudding user response:
You can try with using FormRequest for validation and custom messages. https://laravel.com/docs/8.x/validation#creating-form-requests
use Illuminate\Support\Facades\Validator;
$exampleRequest = new ExampleRequest();
$validator = Validator::make($request->all(), $exampleRequest->rules(), $exampleRequest->messages());
if($validator->fails()){
return response()->json($validator->errors(), 422);
}
This will return JSON response (for an API in this case):
{
"name": [
"First name is required."
]
}
For given rules and messages in ExampleRequest:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
// 'name' => 'required',
];
}
public function messages()
{
return [
'name.required' => 'First name is required.'
];
}