Search code examples
phplaravelphp-carbon

add records from a particular month


I need to add the records for the month of July.

My code: now I can only add the records of the current month

$cobrosm = Cobros::whereBetween('created_at',[
            $carbon->startOfMonth()->toDateString(),
            $carbon->endOfMonth()->toDateString()
       ])->sum('importe');

Solution

  • Try with this code :

    $julyDate = date('Y-07-d');
    $cobrosm = Cobros::whereBetween('created_at',[
            Carbon::createFromFormat('Y-m-d', $julyDate)
                ->firstOfMonth()
                ->toDateString(),
            Carbon::createFromFormat('Y-m-d', $julyDate)
                ->lastOfMonth()
                ->toDateString()
        ])->sum('importe');
    

    For more on Carbon https://carbon.nesbot.com/docs/