Rent available cars from rentals table

I have my table with rentals

id| user_id| car_id | starting_date | ending_date

and here is cars table
id | name

I don’t know how to habndle the situation.. I have N cars, and I want to return only available cars for specific dates.

For example I want to rent a car on this period:
20.02.2018 – 23.02.2018

But I don’t know how to check every case to see if a car is available in that period using Laravel.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use the whereDoesntHave() method. I assume you already have rentals relationship defined:

$date1 = Carbon::parse('20.02.2018')->startOfDay();
$date2 = Carbon::parse('23.02.2018')->endOfDay();
$available = Car::whereDoesntHave('rentals', function($q) use($date1, $date2) {
    $q->whereBetween('starting_date', [$date1, $date2])
      ->orWhereBetween('ending_date', [$date1, $date2])
      ->orWhere(function($q) use($date1, $date2) {
          $q->where('starting_date', '<', $date1)
            ->where('ending_date', '>', $date2);
      });
})
->get();

If you don’t have the relationship, define it in the Car model:
public function rentals()
{
    return $this->hasMany(Rental::class);
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x