Categories : Laravel

Hi, when you create new migration file with unsined big integer column type. Laravel has no validation rule for this type of variable. General integer validation rule is not compatible with this number’s min and max value and length. So if you want to validate unsigned big integer mysql column type in your Laravel project you can use this rule. Otherwise if you validate this value with integer validation rule you will not be able to have numbers more then integer rule’s max value.

What is the limitation of integer rule in laravel?

Laravel’s default integer validation rule uses PHP’s FILTER_VALIDATE_INT rule to validate integer. This rule value range is 0 to 2147483647 but unsigned big integer value range is 0 to 18446744073709551615

Crate a new rule class

php artisan make:rule UnsignedBigIntegerRule

Copy and paste content for this class : UnsignedBigInteger

app/Rules/UnsignedBigIntegerRule.php
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class UnsignedBigIntegerRule implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @param Closure $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ( str_starts_with( $value, '-') || ( strlen($value) > 1 && str_starts_with( $value, '0') ) ) {
            $fail(__('validation.integer', ['attribute' => $attribute]));
        }

        if (!is_numeric($value) || !preg_match('/^[0-9]+$/', $value) ) {
            $fail(__('validation.integer', ['attribute' => $attribute]));
        }

        if ( is_numeric($value) && ( $value > 18446744073709551615 || $value < 0 ) ) {

            $fail(__('validation.between.numeric', [
                'attribute' => $attribute,
                'min' => 0, 
                'max' => 18446744073709551615
            ]));

        }
    }
}

Create Request class to use our new validation rule

php artisan make:request UpdateCustomerPostRequest

Example Class Content

app/Http/Requests/UpdateCustomerPostRequest.php
<?php

namespace App\Http\Requests;

use App\Rules\UnsignedBigIntegerRule;
use Illuminate\Foundation\Http\FormRequest;

class TestIntegerRequest 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 [
            'customer_id' => [
                'required',
                new UnsignedBigIntegerRule(),
            ],
        ];
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *