Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Check if event date range is not already taken

I'm creating calendar for few days events and the events can not overlap. But event can start/end when another event starts/ends.

In Laravel, in my event model table I am storing start and end date of events. How can I check before storing new event do database, if it is valid (is not overlapping with existing events, excluding margin/boundary days) ?

This is the idea

In advance thank You very much for Your help.

like image 855
zyx4sdk Avatar asked Oct 25 '16 16:10

zyx4sdk


2 Answers

You can use following code to get the correct counts for events booked between certain times:

$eventsCount = Events::where(function ($query) use ($startTime, $endTime) {
 $query->where(function ($query) use ($startTime, $endTime) {
    $query->where('start', '>=', $startTime)
            ->where('end', '<', $startTime);
    })
    ->orWhere(function ($query) use ($startTime, $endTime) {
        $query->where('start', '<', $endTime)
                ->where('end', '>=', $endTime);
    });
})->count();
like image 137
Amit Gupta Avatar answered Oct 16 '22 02:10

Amit Gupta


Use it for all variants intersections date ranges. It help for me

$rangeCount = TransferSchedule::where(function ($query) use ($from, $to) {
                $query->where(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $from)
                        ->where('date_to', '>=', $from);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $to)
                        ->where('date_to', '>=', $to);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '>=', $from)
                        ->where('date_to', '<=', $to);
                });
            })->count();
like image 39
Maxim Abdalov Avatar answered Oct 16 '22 01:10

Maxim Abdalov