1
votes

I have the following rule to only set my text field required if online is set to 1.

'required_if:online,1'

Now I'm wondering if it's possible to use this behaviour using a custom rule object, see: https://laravel.com/docs/6.x/validation#using-rule-objects

The following 2 attributes are available in the rule object: Attribute and Value

public function passes($attribute, $value)
{
    //
}

Is it possible to check other fields that are included in the current request using this method?

1

1 Answers

1
votes

A possible solution for this is to extend your custom rule constructor and pass the $request as a param.

CustomRule

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;

class CustomRule implements Rule
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function passes($attribute, $value)
    {
        return ...;
    }

    ...
}

YourController

$request->validate([
    'input1' => ['required', 'string', new CustomRule($request)],
    'input2' => ['required', 'string'],
]);

This was also discussed as an issue Allow custom validation rules access all parameters in laravel/framework