Snippet

Base Rule class for Laravel

app/Rules/Rule.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule as Contract;

abstract class Rule implements Contract
{
    protected string $message;

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

    /**
     * Determines the validation did not pass.
     *
     * @param  string  $message
     * @return bool
     */
    protected function fail(string $message) : bool
    {
        $this->message = $message;

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string|array
     */
    public function message()
    {
        return $this->message;
    }
}

Context

When building custom validation rules on Laravel, you have to declare a message() method that returns your error message. If you have multiple parameters to account for when creating this message, the logic for this method can get messy very quickly. This base class your rules can extend from attempts to solve that by allowing you to specify the error message when you make the rule fail.

Usage

app/Rules/ValidValue.php
<?php

namespace App\Rules;

class ValidValue extends Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($value !== 'value') {
            return $this->fail('You have the wrong value!');
        }

        return true;
    }
}