Search code examples
phplaravelweb-frameworkslaravel-validationlaravel-7

How can I conditionally validate a custom rule in Laravel?


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!


Solution

  • 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!