I have following segment of the validation:
'places' => [
new CompanyHasPlacesRule,
],
and the validation class:
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$company = DB::table('companies')
->select('companies.id', DB::raw('GROUP_CONCAT(places.id) as placeIDs'))
->join('places', 'companies.id', '=', 'places.company_id')
->where('companies.id', $this->data['company_id'])
->groupBy('companies.id')
->first();
if (! $company?->placeIDs && $value === null) {
return;
}
if ($company?->placeIDs && $value === null) {
$fail('Please select place associated with the company.');
}
if ($value && $company->placeIDs) {
$difference = array_diff($value, explode(',', $company->placeIDs));
if (! empty($difference)) {
$fail('Selected company does not have this place assigned.');
}
return;
}
$fail('Selected company does not have this place assigned.');
}
The problem: company doesn't always have a place, but if the company have a place, one or more places needs to be selected - places needs to be validated only if the company have places, and the only way to find out if the company has places is in validation. Is there a way to always validated places even if the places field is not in the request?
'places' => [Required::if(Company::find($this->company_id)->places()->count())]