reaz's avatar
Level 5

How to write a rule object to check parent object start date

Hi, I would like to write a Validation rule where it validates depending on parent start date. for example, a ticket belongs to event. Now when i receive a ticket_id in the request, i would like validate if the parent Event start date and end date is within today. How could write this using the Rule::exists syntax?

Rule::exists('ticket', 'id')->where(
                    function (Builder $query) {
                        $query->where('start', '<', Carbon::now()->toDateTimeString())
                    }
                );
0 likes
1 reply
MohamedTammam's avatar

Create custom rule

'ticket_id' => [
	'required',
	function(string $attribute, mixed $value, Closure $fail) {
		$exists = Ticket::where('id', $value)
				->whereHas(
					'parent', 
					function($q) => $q->where('start', '<', Carbon::now()->toDateTimeString()
				)
				->exists();
		if(!$exists)
			return $fail("The {$attribute} doesn't exists in the date range.");
}]

Please or to participate in this conversation.