Reputation: 399
I have the following Collection file in Laravel, as you can see I have a "totalventa" field, I would like to sum that field of each record in the Collection, but I don't know how it could be, thank you.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\Storage;
class VentaCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function toArray($request)
{
return $this->collection->transform(function($row, $key) {
return [
'id' => $row->id,
'fecha' => date('d/m/Y', strtotime($row->fecha)),
'items' => $row->detalles,
'totalventa' => $row->total(),
'subtotalventa' => $row->subtotal(),
'igvventa' => $row->igv(),
'notas' => $row->notas,
'observaciones' => $row->observaciones,
'pdf' => $row->enlace_pdf,
'estado' => $row->estado,
];
})
}
}
I want to join as one more field of the collection, something like "total sum" ...
$records = Venta::where('tienda_id',$id)
->whereIn('estado', $filtro)
->whereYear('fecha', Carbon::now()->year)
->whereMonth('fecha', Carbon::now()->month)
->orderBy('id', 'desc')
->paginate(env('ITEMS_PER_PAGE', 10));
return new VentaCollection($records);
Upvotes: 0
Views: 875
Reputation: 580
try this
$records_Sum = Venta::where('tienda_id',$id)
->whereIn('estado', $filtro)
->whereYear('fecha', Carbon::now()->year)
->whereMonth('fecha', Carbon::now()->month)
->get()->sum('totalventa');
Upvotes: 1