How to make a custom validation rule in laravel?

Custom Validation

How to make a custom validation rule in laravel. Make Custome validation ruel in laravel .it’s easy to use and greate solution.

Also Read: Explain Contextual Binding and how does it work in Laravel?

  • Run this “php artisan make:rule OlympicYear
  • After that command it generates a file app/Rules/OlympicYear.php
  • We can write rule in the passes() in OlympicYear.php generated file. It will return true or false depending on condition, which is this in our case
    public function passes($attribute, $value)
    {
    return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
    }
  • Next, we can update error message to be this:
    public function message()
    {
    return ':attribute should be a year of Olympic Games';
    }
  • Finally, we use this class in controller’s store() method we have this code:
    public function store(Request $request)
    {
    $this->validate($request, ['year' => new OlympicYear]);

Leave a Reply

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