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);
}
you need to use this command
php artisan make:request StorePostRequest
and put your validation conditions in the rules
function
public function rules(): array
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
also 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)
public function authorize(): bool
{
/* if you haven't checked the authorization, you can return Auth::user(); */
return true;
}