In this article, we are exploring how we can create a custom rule in Laravel and apply to filament forms. We will create a custom Laravel validation rule to ensure that a product’s name is unique within the selected category.

Check out the official docs.

Creation of Rule

First, we need to create a custom validation rule. Run the following command in your terminal:

php artisan make:rule UniqueProductInCategory

The above command will generate the following code:

<?php

namespace App\Rules;

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

class UniqueProductInCategory implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        //
    }
}

Now what we assume is we will get the category id when this rule is invoked. So, for that we will use the constructor() to access that.

......
 public $categoryId;

    public function __construct($categoryId)
    {
        $this->categoryId = $categoryId;
    }
......

Read more filament tips and tricks

Modify Validate method

Now, we will add the code for validation inside the validate() method.

 public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (Product::where('category_id', $this->categoryId)->where('name', $value)->exists()) {
            $fail('The product name must be unique within the selected category.');
        }
    }

We checked the value in our product table and if it fails, we just return the message. So, our validation rule is ready.

Implement validation rule in filament

Now, its turn to implement this rule. So, for that we will chain the rules() method on our filament form components.

.....
Forms\Components\TextInput::make("name")
                                ->label(__("Name"))
                                ->required()
                                ->rules(function(callable $get){
                                    return [new UniqueProductInCategory($get('category_id'))];
                                })

....

You can see , we just chained the rules() method and there we use callable $get to get the form values for selected category_id and pass it to our validation class.

Conclusion

So, in this way we can create a custom rule in Laravel and implement it on filament forms. If you have any queries, just comment down below.

Similar Posts

Leave a Reply

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