How to create custom rules in Laravel8

Any form data should be validate from the server language. In Laravel application, you can simply validate the form data using validate() method. Laravel provides many default validation type by which you can directly add these validation for the field.

/**
 * Store a data
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|unique:posts|min:6|max:255',
        'author' => 'required|email',
        'body' => 'required',
    ]);

    // save data...
}

Bu sometimes, you need complex validation for specific field. You might need to write custom logic. For that you need to generate Rule class and apply for the field.

To generate a new rule, you may use the below artisan command.

php artisan make:rule DivisibleByNumber

This will create new Rule class at app/Rules directory.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class DivisibleByNumber implements Rule
{
    /**
     * Number passed from controller.
     *
     */
    protected $multiplier;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($multiplier)
    {
        $this->multiplier = $multiplier;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value % $this->multiplier === 0;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The quantity should be multiple to '.$this->multiplier;
    }
}

And then you can use class in the validation method.

use App\Rules\DivisibleByNumber;

/**
 * Store a data
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $request->validate([
        'number' => ['required', new DivisibleByNumber(5)], // the number should be divisible by 5
    ]);

    // save data...
}

In addition to above method, you can also validate adding the function if you only want the validation once in the application. The three parameters are attribute's name, the attribute's value, and the third one is $fail callback that should be called if validation fails.

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'number' => [
        'required',
        function ($attribute, $value, $fail) {
            if ($value % 5 === 0) {
                $fail('The '.$attribute.' should be multiple to 5');
            }
        },
    ],
]);

So these ways you can create custom rules in Laravel application. I hope you liked this article and will help you.

Tags: