问题
I need to access $request->important
in passes method. I need it to validate name based on this value
class TestCustom implements Rule
{
public function passes($attribute, $value)
{
//
}
public function message()
{
return 'some txt';
}
}
Used like this:
use App\Rules\TestCustom;
$request->validate([
'name' => ['required', new TestCustom],
'important' => ['required', 'string'],
]);
回答1:
It's much better to pass data to rule constructor and use it inside rule afterwards. This way you can use rule to validate different data sources, in case if it comes not from request.
class TestCustom implements Rule
{
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function passes($attribute, $value)
{
// Use $this->data['important'] for validation
}
public function message()
{
return 'some txt';
}
}
Then pass data to rule:
use App\Rules\TestCustom;
$request->validate([
'name' => ['required', new TestCustom($request->all())],
'important' => ['required', 'string'],
]);
回答2:
use Input
facade-
Input::get('important');
来源:https://stackoverflow.com/questions/48420488/access-to-another-requested-input-in-custom-rule-class-laravel