Lisa
Lisa

Reputation: 2139

Custom Validation Replacers in Laravel 5.1

I am trying to create a custom validation replacer in my Laravel 5.1 application.

I currently have

Validator::replacer('year', 'App\CustomValidators@replaceYear');

in my AppServiceProvider file with the corresponding living in my custom class. However when I include :year in a validation message, it is not replaced. what am I missing?

Here's my replacer function.

public function replaceYear($message, $attribute, $rule, $parameters)
{
    return str_replace([':year'], $parameters, $message);
}

Upvotes: 4

Views: 4912

Answers (1)

Lisa
Lisa

Reputation: 2139

What I really should have done was set up my replacer similar to this:

Validator::replacer('dateInYear', 'App\CustomValidators@replaceDateInYear');

the dateInYear name corresponds with the name of the custom validation rule that I set up. What I ultimately ended up doing, though, was extending the validator class so I no longer have to declare every single custom rule and replacer. My validator class now looks something like this:

<?php

namespace App\Services;

use Carbon\Carbon;
use \Illuminate\Validation\Validator;

class CustomValidator extends Validator
{

    /**
     * The new validation rule I want to apply to a field. In this instance,
     * I want to check if a submitted date is within a specific year
     */
    protected function validateDateInYear($attribute, $value, $parameters, $validator)
    {
        $date = Carbon::createFromFormat('m/d/Y', $value)->startOfDay();

        if ($date->year == $parameters[0]) {
            return true;
        }
        return false;
    }

    //Custom Replacers
    /**
     * The replacer that goes with my specific custom validator. They
     * should be named the same with a different prefix word so laravel
     * knows they should be run together.
     */
    protected function replaceDateInYear($message, $attribute, $rule, $parameters)
    {
        //All custom placeholders that live in the message for
        //this rule should live in the first parameter of str_replace
        return str_replace([':year'], $parameters, $message);
    }
}

This lets me leave my AppServiceProvider file alone for the most part, only needing registering the new validation class, which I really could do in any service provider.

Laravel's documentation is exceptionally lacking on what needs to happen for replacers, so I hope this helps someone down the road.

Upvotes: 12

Related Questions