Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to another requested input in custom rule class - Laravel

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'],
]);
like image 274
Bolek Lolek Avatar asked Jan 24 '18 10:01

Bolek Lolek


2 Answers

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'],
]);
like image 192
Vedmant Avatar answered Sep 28 '22 08:09

Vedmant


use Input facade-

Input::get('important');
like image 36
Sohel0415 Avatar answered Sep 28 '22 09:09

Sohel0415