How to validate plural word in laravel ?

Plural word validation is not among the large set of validation rules provided by laravel. So, it's little bit tricky to validate if input word is plural. Checking plural or singular is one of the complex task in grammer since there are large set of rules and some ambiguity as well. However, laravel provides functions to transform words into singular and plural words.

We will use helper function str_plural function which ultimately calls the Str::plural() function.

if (! function_exists('str_plural')) {
    /**
     * Get the plural form of an English word.
     *
     * @param  string  $value
     * @param  int     $count
     * @return string
     */
    function str_plural($value, $count = 2)
    {
        return Str::plural($value, $count);
    }
}

Now, lets create a custom validation rule IsPlural and then we will add the logic to check plural.

Also Read: How to create custom validation rules in laravel ?

We will use artisan command to create a custom rule.

php artisan make:rule IsPlural

This will create IsPlural.php file inside app/Rules/ directory. Our custom validation rule will be like this:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class IsPlural implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value === str_plural($value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute needs to be a plural!';
    }
}

We have created the validation rule to check plural word. Now, We can use this rule in the validation like this:

'name' => ['required', 'string', 'max:255', new IsPlural()]

And most important thing, never forgot to imort the IsPlural where you will validate the request.

use App\Rules\IsPlural;

In this way, we can validate the plural word and validation only passed if we enter plural word in the form request. It looked complex but its really simple in laravel.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback