Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking dates if between range of dates in Laravel 5

I have a booked table with start and end column as datestamps;

I know that this

$start = "2015-07-12 01:00:00";
$end = "2015-07-12 02:00:00";

$users = DB::table('booked')
                    ->whereBetween('start', [$start, $end])->get();

checks for any dates in start column that falls within $start and $end.

What I want is actually the other way.

Am having difficulty checking for $start and $end date variables occurrences in start and end columns in book table.

like image 396
shaNnex Avatar asked Dec 15 '22 13:12

shaNnex


2 Answers

// make sure $from is before $till, because they are probably provided as input
$from = min($start, $end);
$till = max($start, $end);

// then simply
DB::table('booked')
     ->where('start', '<=', $from)
     ->where('end', '>=', $till)
     ->get();

It will return rows matching $from-$till period contained in start-end period:

    start                     end
      |------------------------|
         |----------------|
       $from            $till
like image 143
Jarek Tkaczyk Avatar answered Dec 25 '22 09:12

Jarek Tkaczyk


Please Try under given code this will check is requested dates time are already book or not, if any time slot is booked then it will return 1 otherwise 0 :

$start = $request->start_date; 
$end = $request->end_date; 
DB::table('booked')->where(function ($query) use ($start, $end) {

    $query->where(function ($q) use ($start, $end) {
        $q->where('start', '>=', $start)
           ->where('start', '<', $end);

    })->orWhere(function ($q) use ($start, $end) {
        $q->where('start', '<=', $start)
           ->where('end', '>', $end);

    })->orWhere(function ($q) use ($start, $end) {
        $q->where('end', '>', $start)
           ->where('end', '<=', $end);

    })->orWhere(function ($q) use ($start, $end) {
        $q->where('start', '>=', $start)
           ->where('end', '<=', $end);
    });

})->count();
like image 30
Er Parwinder Hirkewal Avatar answered Dec 25 '22 11:12

Er Parwinder Hirkewal