问题
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