In my controller I validate fields of my json request. To obey single responsibility, I want to create a custom Validator class and put following code to my validator class.
When I type:
php artisan make:validator MyValidator
I found out that validator class doesn’t exist in newer versions. So where should I put following code in Laravel 10? Keeping in controller doesn’t seem a best practice.
$validator = Validator::make($request->json()->all(), [
"field1" => "required",
"field2" => "required|numeric",
]);
if ($validator->fails()) {
return response()->json([
'message' => __("Please fill required fields"),
'errors' => $validator->errors(),
], 422);
}
2
Answers
you need to use this command
php artisan make:request StorePostRequest
and put your validation conditions in the
rules
functionalso you need to change the return of the another function in that file which is named
authorize
: (because we usually check the permission on the router file we directly return true)In the newer versions of laravel you can follow these steps.
Run the command
and put your validation conditions in the rules function
Ensure the authorize method returns true
Then in your store method you can have the