Laravel Form Validation with example

There are a bunch of ways to handle Form Validation through Laravel. It just depends on the developer. The robust ways to form validation is by creating a form request by the artisan command. It will help to separate the validation logic from the controller. Another way is by adding manual validatation rules within the method.

Table of content

Manual Form Validation

The easiest way to validate the form validation is by using the Validator facade. You can define your validation rules in your method with the Validator facade.

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required', 
        'email' => 'required|email', 
        'subject' => 'required'
    ]);

    if ($validator->fails()) {
        return redirect('contact-form')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the contact form data 
    // and redirect user to thank you page
}

If you are using the latest version of Laravel then there is another way to add manual form validation without using the Validator facade. Laravel latest version using the ValidatesRequests trait in the controller. And you can modify the above validation rules to the newer version like the below codes.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required', 
        'email' => 'required|email', 
        'subject' => 'required'
    ]);

    // Store the contact form data 
    // and redirect user to thank you page
}

The above code will go through the defined rules for the particular request and will redirect back to the page if the request failed. You can display the errors by adding the following codes to your blade template.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Or if you are using the latest version of Laravel, then you can use the @errror directive to display a single error.

<div class="col-md-6">
    <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">

    @error('email')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
    @enderror
</div>

Validation by Creating Form Request

Laravel has many artisan commands to increase productivity. The make:request command is used for creating a form request. This command will make a separate file at app/Http/Requests directory.

php artisan make:request ContactFormRequest

Above command will create a ContactFormRequest class at Requests directory. By default, this class holds two methods authorize() and rules().

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

You can define your validation rules at rules() method. If you want to add custom messages for your defined rule(s), then you can add messages() method too.

....

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' => 'required', 
        'email' => 'required|email', 
        'subject' => 'required'
    ];
}

....

Now just apply the ContactFormRequest class to your controller. Let’s revamp the previous store method with the new form request class. This class will automatically redirect back to the previous page if the validation fails.

public function store(\App\Http\Requests\ContactFormRequest $request)
{
    // Store the contact form data 
    // and redirect user to thank you page
}

Form Validation before Submit

Form validation before submitting or we can say ajax based form validation. Laravel Jsvalidation package is beautiful for ajax based form validation that will use the existing form validation request class and auto-generate the javascript validation rules. It’s very easy to apply to the particular form.

{!! JsValidator::formRequest('App\Http\Requests\ContactFormRequest', '#contactForm') !!}

Laravel JsValidation plugin will automatically take care of the error highlighting. This package also provides the configuration settings that you can change according to your need.