rfpdl
rfpdl

Reputation: 964

Laravel - validate array to existing array and null

Currently making API endpoints for repetition schedule, but I am having an issue in validating array to make sure it exists in the preset array:

For example, the repeat_day values must have correct days

This is the API request:

{
   "repeat_by": "daily",
   "repeat_day": [
       "Sunday",
       "xxx" 
   ],
   "repeat_date": [],
   "repeat_week": [],
   "repeat_month": []
}

This is the StoreUpdateScheduleRequest

public function __construct()
{
    $this->dayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    //and some other array
}

public function rules()
{
    $repeatDayRule = request()->get('repeat_by') == "daily" ? ['required', Rule::in($this->dayArray)] : '';
    //and some other validation rules

    return [
        "repeat_day.*" => $repeatDayRule
        "repeat_date.*" => $repeatDateRule
        "repeat_week.*" => $repeatWeekRule
        "repeat_month.*" => $repeatMonthRule
    ];
}

My problem is that, when I provide null or empty array, the validation passes which it should fail.

{
    "repeat_by": "daily"
    "repeat_day": null //or even []
}

Note:


Thanks in advance! Cheers!

Upvotes: 0

Views: 731

Answers (2)

Paul Carlo Tordecilla
Paul Carlo Tordecilla

Reputation: 60

'repeat_day' => 'nullable',

insert this inside of your request validation

Upvotes: 0

IlGala
IlGala

Reputation: 3419

You should implement both rules when validating that array with the filled rule. Something like this:

return [
    "repeat_day" => 'array|filled',
    "repeat_day.*" => $repeatDayRule,
    "repeat_date" => 'array|filled',
    "repeat_date.*" => $repeatDateRule,
    "repeat_week" => 'array|filled',
    "repeat_week.*" => $repeatWeekRule,
    "repeat_month" => 'array|filled',
    "repeat_month.*" => $repeatMonthRule
];

With this code you will check that, for example, repeat_day is an array and it's filled. With the next sentence you will check that its values are valid with the $repeatDayRule

Upvotes: 1

Related Questions