Access to another requested input in custom rule class - Laravel

落爺英雄遲暮 提交于 2021-02-07 19:12:47

问题


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

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