I am trying to get data from DB based on the input date, If there is data with a previous date then it will give me output.
But say the current date is 2024-02-22 and DB doesn't have data for 2024-02-21 or 20, but has data for 19, this means we need to find data which is close to the current date, then how can I get it? my current code gets only the previous date, but need to find data which is close to current date,
foreach ($file as $row) {
$current_date = Carbon::createFromFormat('d-M-Y', str_replace(' ', '', $row[2]))->format('Y-m-d');
$carbonDate = Carbon::parse($current_date);
$previous_date = $carbonDate->subDay()->format('Y-m-d');
//Now find data of the previous day with symbol and date.
$pd = EodBhavData::where('symbol', $row[0])->where('date', $previous_date)->first();
\\ Compare code and calculations...
}
Change
where('date', $previous_date)
to
where('date', '<=', $previous_date)
or
whereDate('date', '<=', $previous_date)
Your current condition is only pointing to exact $previous_date
that is why only "2024-02-21" is retrieved.
Personally, I would use whereDate