How to send Multiple parameters in passes function of custom validation rule

自古美人都是妖i 提交于 2021-02-05 07:14:26

问题


I am implementing a custom validation rule which should take another parameter with attribute and value in passes function of custom validation rule. As we implement Rule interface while writing custom validations, it does not allow us to add third parameter in passes function but I need third parameter. Moreover, I will feel happy if anyone can guide me about the best practice of including database in rule. Either we should include only desired model in rule if we need a table in custom validation rule or we should use Illuminate\Support\Facades\DB while writing queries in validation rules. I want the following format of passes function

public function passes($attribute, $value,$extraparam)
{
    /*Code here*/
}

回答1:


You could pass the extra parameter as an argument to the Rule's constructor

use App\Rules\Uppercase;

$request->validate([
    'name' => ['required', new Uppercase($param)],
]);

so you could modify your Rule's class as

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    protected $extraParam;

    public function __construct($param)
    {
        $this->extraParam = $param;
    }

    public function passes($attribute, $value)
    {
        // Access the extra param as $this->extraParam
        return strtoupper($value) === $value;
    }
}


来源:https://stackoverflow.com/questions/49272643/how-to-send-multiple-parameters-in-passes-function-of-custom-validation-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!