0

In my controller I have a store method that is validating the request data:

$request->validate([
    'title' => 'required',
    'description' => 'required',
    'date' => [
        'required',
        new DateFormatRule
    ],
    'closed' => 'nullable',
    'time_start' => 'required_if:closed,0',
    'time_end' => [
        'required_if:closed,0',
        new TimeDurationRule($request->time_start)
    ],
]);

closed is a boolean. If closed is false, the time_start and time_end fields are required. This seems to be working as expected.

However, if I submit a request with closed as true, I am getting caught in my custom TimeDurationRule:

'time_end' => [
    'required_if:closed,0',
    new TimeDurationRule($request->time_start)
], 

How can I make new TimeDurationRule($request->time_start) conditional? For example, if closed is true, I am manually setting time_end to null so time_start/time_end do not need a value (not required).

If I comment my custom rule out, everything works as expected.

Thank you for any suggestions!

1 Answer 1

1

You can pass $request->closed to your TimeDurationRule and then in the passes method of the rule, you can do something like this:

class TimeDurationRule implements Rule
{
    public $closed;

    public function __construct(/*all needed parameters*/, $closed)
    {
        $this->closed = $closed;
    }

    public function passes($attribute, $value)
    {
        if(!$closed){ 
         return true
        }

        // the rest of validation logic
    }
}

And then

new TimeDurationRule(/*all needed parameters*/, $request->closed)

You can read more about it here as well: https://laracasts.com/discuss/channels/laravel/create-custom-validation-rule-with-additional-parameters-implement-in-request

Hope it helps!

Sign up to request clarification or add additional context in comments.

2 Comments

I feel really silly. I didn't realize I could pass additional params to the rule like that. Thought it was just a 1:1 rule that only evaluated the one argument. Thank you for your help!
@Damon no problem! Rule is just a class like all the others, so you can do whatever you want with the constructor and similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.