I would like to move this code to the App\Rule:
//Currently in class AppServiceProvider extends ServiceProvider
Validator::extend('empty_if', function ($attribute, $value, $parameters, $validator) {
return ($value != '' && request($parameters[0]) != '') ? false : true;
});
So that it should be this:
//in: App\Rules\EmptyIf
public function passes($attribute, $value, $parameters)
{
return ($value != '' && request($parameters[0]) != '') ? false : true;
}
But my problem is, that I cannot pass $parameters with
Validator::extend('empty_if', 'App\Rules\EmptyIf@passes');
How would you pass parameters to Laravel Rule?
You can access the passed param in the Rule's constructor, so just set a globally scoped variable and now you can reference it inside of the passes() method. You could even use the same approach to have the value in the validator message. Save this answer.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
Here is a simpler and updated way of accomplishing this, without extending the validator. You can access the passed param in the Rule's constructor, so just set a globally scoped variable and now you can reference it inside of the passes() method. You could even use the same approach to have the value in the validator message.
The validate call:
case 'measurement':
$request->validate([
'updates.*.value' => [
new Measurement('foo-bar'),
],
]);
break;
The Rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Measurement implements Rule
{
/**
* Create a new rule instance.
*
* @param $param
*/
public function __construct($param)
{
$this->type = $param;
}
public $type;
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @return bool
*/
public function passes($attribute, $value)
{
dd($this->type, 'params');
return;
}
You can pass parameters with constructor in Rule
public function __construct($params)
{
$this->params = $params;
}
Then access parameters in passes method
public function passes($attribute, $value)
{
//access params with $this->params
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With