Validate Laravel Requests

Posted on

In Laravel there are many different ways to validate user input, and one of these is Request validation. This method is best for when you are validating something that isnt a model, like for example a contact form. Validating requests this way will allow you to move all your validation logic out of your controllers and into its own Request Validation class. Remember Slim Controllers/ Fat Models. See below.

Below is an example of what we want to avoid, a bloated controller! What is bad about this is not only the amount of extra code that is introduced, but what if you would like to validate the same information on two different routes? You will have to write the logic again, and if you want to change this logic you are going to have to change it in two different places.

class ContactController {    

    public function processSubmission($request)

    {

        $rules = array(

             'name' => 'required',

             'email' => 'required|email'

        );

        $validator = Validator::make($request::all(), $rules);

       if($validator->fails()) {

            $messages = $validator->messages();

            return redirect('contact-us')->with('messages', $messages)

        } else {

            // do something else

        }

    }

}

Now what we can do is create a new FormRequest class via the artisan command php artisan make:request .

class ContactController {    

// Note the type of request which is getting passed into this function ( FormRequest )

    public function processSubmission(FormRequest $request)
    
    {
        // All the validation logic has been moved out into the new FormRequest class leaving this method to only hav the relevant logic in it
    }
}

All the validating of the form has already been done before this method is hit. Cool eh?