0
votes

I am writing a custom validation rule. In my form I validate fields using rules with a validation group called 'my-event'. One of my rules is if a checkbox is checked called 'other', then the text field 'other' needs to be filled in.

My request gets validated against these rules:

EventRequest.php

 public function rules()
    {
        return [
            'my-event.event-types' => 'required'
            'my-event.event-type-other' => [
                'string', new CheckboxIsValid($checkboxArray)
            ],
        ];
    }

CheckboxIsValid is a helper class that I have written that implements Laravel's rule:

class CheckboxIsValid implements Rule
{

    public $checkboxArray;

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

    public function passes($attribute, $value)
    {
        if(in_array('other', $this->checkboxArray)) {
            if($value) {
                return true;
            }
        }
        return false;
    }

}

This checks whether 'other' is in my array of checked checkboxes. I would like to pass in the value of my-event.event-types. How do I do this?

1

1 Answers

0
votes

EventRequest.php extends FormRequest, which extends Request, which will give access to the other form fields values:

$this->validationData()

I have accessed this in EventRequest.php like so:

// Instantiate it in case form is submitted without any event types

$eventTypes = [];

if(isset($this->validationData()['my-event']['event-types'])){
            $eventTypes = $this->validationData()['my-event']['event-types'];
        }

And then this can be passed into my Rule:

 'my-event.event-types-other' => [
            new CheckboxIsValid($teachingMethods, 'other')
        ],

And in the constructor of CheckboxIsValid:

public $checkboxArray;
public $field;

public function __construct($checkboxArray, $field)
{
    $this->checkboxArray = $checkboxArray;
    $this->field = $field;
}