skip to Main Content

I have a car model and an order model, i need a query that will filter the list of cars that are not rented between two dates, i’m lacking the logic to get the answer right what i came up with is this :

$query->whereHas('orders', function ($query) use ($date, $data) 
{
  $query->whereNotBetween('rental_start_date', $fromDate, $toDate])
        ->whereNotBetween('rental_end_date', $fromDate, $toDate])
        ->whereDate('rental_start_date', '<>', $fromDate)
        ->whereDate('rental_end_date', '<>', $toDate);
}```

2

Answers


  1. Use whereDoesntHave() to filter this

    $query->whereDoesntHave('orders', function ($query) use ($fromDate, $toDate) {
      $query->whereBetween('rental_start_date', [$fromDate, $toDate])
            ->orWhereBetween('rental_end_date', [$fromDate, $toDate])
            ->orWhere(function($query) use ($fromDate, $toDate) {
                $query->where('rental_start_date', '<', $fromDate)
                      ->where('rental_end_date', '>', $toDate);
            });
    });
    
    Login or Signup to reply.
  2. I think you can use to filter the list of cars that are not rented between two dates like this:

    $query->whereDoesntHave('orders', function ($query) use ($fromDate, $toDate) {
      $query->whereBetween('rental_start_date', [$fromDate, $toDate]);
      $query->orWhereBetween('rental_end_date', [$fromDate, $toDate]);
    });
    

    This query will first get all of the orders that were placed between the two dates. It will then use the whereDoesntHave() method to filter out any cars that have an order in this date range. This will leave you with a list of cars that are not rented between the two dates.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search