skip to Main Content

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


  1. 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;
    }
    
    Login or Signup to reply.
  2. In the newer versions of laravel you can follow these steps.
    Run the command

    php artisan make:request ProjectStoreRequest
    

    and put your validation conditions in the rules function

    public function rules(): array
    {
        return [
         "field1" => "required",
        "field2" => "required|numeric"
        ];
    }
    

    Ensure the authorize method returns true

    public function authorize(): bool
    {
        /* if you haven't checked the authorization, you can return return Auth::user(); */
        return true;
    }
    

    Then in your store method you can have the

    use AppHttpRequestsProjectStoreRequest;
    
    public function store(ProjectStoreRequest $request)
    {
        // Validation passed, you can access validated data using $request
        $data = $request->validated();
    
        // Create or store the data in your database
        // ...
    
        return response()->json(['message' => 'Data stored successfully'], 200);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search