Home > database >  Filter records by interval date in Laravel
Filter records by interval date in Laravel

Time:04-14

I'm creating a filter to get expenses on a Credit Card, to generate a invoice. But I only made it work filtering by month and year. I need get the records on days interval, and than, month and year.

For example:

  • Table: credit_cards
  • Collumn: close_invoice (day 25)

How do I get all expenses between day 25 of previous month and the next day 25?

This is my query filtering by month:

    $thisMonth = $now->format('m');
    $thisYear = $now->format('Y');

    $cc_expenses = Expense::where([
        ['bank_id', $bank->id],
        ['payment_method', 1],
        ['parcels', NULL]
    ])
        ->whereYear('date', $thisYear)
        ->whereMonth('date', $thisMonth)
        ->get();

But this way I don't get the records between day 25 and the last day of the previous month.

Tks advance!

CodePudding user response:

You can use

$previousMonthLastDay = now()->subMonth()->setDay(25)->setHour(0)->setMinute(0)->setSecond(0);

 ->whereBetween('date', [$previousMonthLastDay, now()])

I think nobody need to set future time from now, but if you need, you can do like $previousMonthLastDay without subMonth()

if your now date is 2022-04-13 12:22:10 , $previousMonthLastDay will be like 2022-04-25 00:00:00

  • Related