I am trying to get the expired listings based on the availability periods, there are 3 different available periods. a row should only be returned if the latest not null to_date_* for that row is before now.
A sample data:
| id | from_date_1 | to_date_1 | from_date_2 | to_date_2 | from_date_3 | to_date_3 |
|---|---|---|---|---|---|---|
| 1 | 2021-06-10 | 2021-08-15 | 2021-08-16 | 2021-08-31 | 2021-09-01 | 2021-09-15 |
| 2 | 2021-06-25 | 2021-08-10 | 2021-08-11 | 2021-08-25 | NULL | NULL |
| 3 | 2021-06-25 | 2021-08-20 | NULL | NULL | NULL | NULL |
My SQL Query is:
$listings = collect();
$all_listings = Listing::query()
->where('vendor_id', $vendor->id)
->where('is_deleted', 0)
->where('is_published', 1)
->where('is_approved', 1)
->where('lease_term', '!=', 'long_term')
->orderBy('created_at', 'desc')
->paginate(10);
foreach($all_listings as $lis)
{
if($lis->to_date_3 != null && ($lis->to_date_3 < \Carbon\Carbon::now()->format('Y-m-d')))
{
$listings->add($lis);
continue;
}
elseif($lis->to_date_2 != null && ($lis->to_date_2 < \Carbon\Carbon::now()->format('Y-m-d')))
{
$listings->add($lis);
continue;
}
elseif($lis->to_date_1 < \Carbon\Carbon::now()->format('Y-m-d'))
{
$listings->add($lis);
}
}
The result should be:
| id | from_date_1 | to_date_1 | from_date_2 | to_date_2 | from_date_3 | to_date_3 |
|---|---|---|---|---|---|---|
| 3 | 2021-06-25 | 2021-08-20 | NULL | NULL | NULL | NULL |
However, the query is returning all the 3 listings. how can I fix the query to get the correct result?


