Home » Php » php – Wrong records when filtering date

php – Wrong records when filtering date

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have strange problem when i filter in related models by date,
consider this code :

function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }


    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}

if I filtering yesterday date 17/02/20; it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

How to&Answers:

remove greater than and less than sign so that you can get specific date result

function applyDepositOnRangeFilter($query, $request)
{
if ($request->has('deposit_at_from')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_from'));
    });
}


if ($request->has('deposit_at_to')) {
    $query->whereHas('deposits', function ($query) use ($request) {
        $query->whereDate('created_at', '=', $request->input('deposit_at_to'));
    });
 }
}

Answer:

you are searching ranges, so it is logical you get multiple dates. also on input you need to have both dates set to limit lower and upper range limit. in your setup you need to send both 16/02/20 and 17/02/20 to receive records for 16/02/20.

so check that both values are available if you need to get a specific range.

if ($request->has('deposit_at_from') && $request->has('deposit_at_to') {
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));

} 

or just use one field for date filtering of you want a single date result and do raw filter:

$query->where(DB::raw("DATE(created_at) = '".date('Y-m-d', $request->input('deposit_date')."'"));

Answer:

Sorry guys but i figure it out, this is what works for me for getting range:

  $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from')) 
            ->whereDate('created_at', '<=', $request->input('deposit_at_to'));
  })

if you wonder the laravel ver is 5.6,

Thank you all :-))