Home Rent available cars from rentals table
Reply: 1

Rent available cars from rentals table

Rince1934
1#
Rince1934 Published in 2018-02-14 18:47:15Z

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.

Alexey Mezenin
2#
Alexey Mezenin Reply to 2018-02-14 19:15:44Z

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);
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298556 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO