Laravel Form Validation Tutorial with example | All about Validation in Laravel 10

By Ved Prakash N | Dec 02, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-form-validation-tutorial-with-example

Laravel Form Validation Tutorial with example step by step.


In this post, we will be learning all about Laravel Form Validation. There are many methods to do validations in Laravel. 

This form validation happens on the FORM Submit in Laravel and all the validation codes are written in Controller.

Let's get started.

1. Create Validation

Example 1:To create Validation Rule write inside controller

$request->validate([
    'name' => 'required|max:255',
    'product_code' => 'required|max:255',
    'price' => 'required|decimal:2',
    'stock' => 'required|integer',
    'is_active' => 'sometimes|boolean',
]);


Example 2: To create Validation Rule write inside controller

$request->validate([
    'name' => ['required','max:255'],
    'product_code' => ['required','max:255'],
    'price' => [
        'required',
        'decimal:2'
    ],
    'stock' => ['required','integer'],
    'is_active' => 'sometimes|boolean',
]);


Example 3: Make Validation with a Customized Error Message

Write the custom message with the Validation inside the controller.

$request->validate([
    'name' => 'required|max:255',
    'product_code' => 'required|max:255',
    'price' => 'required|numeric',
    'stock' => 'required|integer',
    'is_active' => 'sometimes|boolean',
], [
    'name.required' => 'The name field is required.',
    'name.max' => 'The name must not exceed 255 characters.',
    'product_code.required' => 'The product code field is required.',
    'product_code.max' => 'The product code must not exceed 255 characters.',
    'price.required' => 'The price field is required.',
    'price.numeric' => 'The price must be a number.',
    'stock.required' => 'The stock field is required.',
    'stock.integer' => 'The stock must be an integer.',
    'is_active.boolean' => 'The is active field must be a boolean value.',
]);


2. Create Validation Using Validator Facade

Write the validation using the "Validator Facade" inside the Laravel Controller.

Example 1: Make Validation with Validator Facade

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'name' => 'required|max:255',
    'product_code' => 'required|max:255',
    'price' => 'required|numeric',
    'stock' => 'required|integer',
    'is_active' => 'sometimes|boolean',
]);

if($validator->fails()){

  return redirect()->back()->withErrors($validator->errors())->withInput();
}


Example 2: Make Validation with Validator Facade

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'name' => ['required','max:255'],
    'product_code' => ['required','max:255'],
    'price' => ['required','numeric'],
    'stock' => ['required','integer'],
    'is_active' => 'sometimes|boolean',
]);

if($validator->fails()){

  return redirect()->back()->withErrors($validator)->withInput();
}


Example 3: Make Validation with Customized Error Message using Validator Facade

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
                'name' => ['required','max:255'],
                'product_code' => ['required','max:255'],
                'price' => ['required','numeric'],
                'stock' => ['required','integer'],
                'is_active' => 'nullable|boolean',
            ],[
                'name.required' => 'The name field is required.',
                'name.max' => 'The name must not exceed 255 characters.',
                'product_code.required' => 'The product code field is required.',
                'product_code.max' => 'The product code must not exceed 255 characters.',
                'price.required' => 'The price field is required.',
                'price.numeric' => 'The price must be a number.',
                'stock.required' => 'The stock field is required.',
                'stock.integer' => 'The stock must be an integer.',
                'is_active.boolean' => 'The is active field must be a boolean value.',
            ]);

if($validator->fails()){

  return redirect()->back()->withErrors($validator)->withInput();
}


3. Displaying The Validation Errors

You can write the below code in the blade files as shown below:

Example 1: Using foreach loop show all messages.

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


Example 2: Show each field error message.

@error('name') <span class="text-danger">{{$message}}</span> @enderror

@error('product_code') <span class="text-danger">{{$message}}</span> @enderror

@error('price') <span class="text-danger">{{$message}}</span> @enderror


4. Form Request Validation in Laravel

Step 1: Creating Form Requests using make:request Artisan CLI Command as follows:

php artisan make:request ProductFormRequest

This will create a new file inside App\Http\Requests folder named as ProductFormRequest.

Step 2: Open the Form Request file in following path : app/ Http/ Requests/ ProductFormRequest.php and paste the below code

In this form request validation file, the authorize() method is to set to "true" and in the rules() method the validation logic.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'max:255'
            ],
            'product_code' => [
                'required',
                'max:255'
            ],
            'price' => [
                'required',
                'nemuric'
            ],
            'stock' => [
                'required',
                'integer'
            ],
            'is_active' => [
                'nullable',
                'boolean'
            ],
        ];
    }
}


STEP 3: Customizing The Error Messages

Now Let's add the custom error message in the above same ProductFormRequest.php file.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductFormRequest extends FormRequest
{

    //... your existing rules
    //... your existing rules

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.required' => 'The name field is required.',
            'name.max' => 'The name must not exceed 255 characters.',
            'product_code.required' => 'The product code field is required.',
            'product_code.max' => 'The product code must not exceed 255 characters.',
            'price.required' => 'The price field is required.',
            'price.numeric' => 'The price must be a number.',
            'stock.required' => 'The stock field is required.',
            'stock.integer' => 'The stock must be an integer.',
            'is_active.boolean' => 'The is active field must be a boolean value.',
        ];
    }
}


STEP 4: Preparing Input For Validation

If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method.

In this prepareForValidation() method, I have shown an example of a product slug where we get the "Product Name" ($this->name) and make it a slug using Str::slug() method and merge the "slug" with FormRequest using merge() function.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

class ProductFormRequest extends FormRequest
{

    //... your existing code
    //... your existing code
    //... your existing code

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'slug' => Str::slug($this->name),
        ]);
    }
}


I hope this helps you. Thanks for reading.

https://www.fundaofwebit.com/post/laravel-form-validation-tutorial-with-example

Share this blog on social platforms