AlmoDev
AlmoDev

Reputation: 969

avoid time/date overlapping in mysql (laravel)

I have an iOS app where users can reserve a car either daily or hourly and if a user reserves one car other user can't reserve it till the first reservation is over. I'm using Laravel as the API to save data to MySQL database.

The format of time and date are like this 27 Dec 2016 15:21. I'm saving the data

 public function requested(Request $request)
{
  $time = new Reservation();
  $time->from_date = $request->from_date;
  $time->to_date = $request->to_date;
  $time->from_time = $request->from_time;
  $time->to_time = $request->to_time;

}

but this won't prevent time overlapping for sure so I tried this

 $carCount = Reservation::where(

  function ($query) use ($startTime, $endTime) {
            $query->where('from_time', '<', $endTime)
                ->where('to_time', '>', $startTime);
        }
    )->count();


    if ($carCount > 0) {
        return response()->json(['request' => 'no']); // this response just to check 
    } else {
        $carRoom->save();
        response()->json(['request' => 'yes']);
    }

then I thought this isn't working because of date/time format. But I wanted to make sure what format I should convert the date in laravel?

this is my migration for Reservation:

         $table->string('from_date')->nullable();
        $table->string('to_date')->nullable();

        $table->string('from_time')->nullable();
        $table->string('to_time')->nullable();

I made the string because I wasn't sure if Time or anything is the right one

My main question is how can I avoid time and date overlapping in my app's database?

Upvotes: 1

Views: 578

Answers (1)

arcanine
arcanine

Reputation: 1953

Store the dates in the database as timestamps then your query should work as intended then convert the incoming dates:

27 Dec 2016 15:21

to timestamps using strtotime() or with datetime objects both are part of PHP check the PHP documentation to see more information.

Upvotes: 1

Related Questions