Add property to Eloquent object in Laravel

1

Using Laravel I query a table called Purchasing that extracts the fields purchase_id, product_name, price, purchase_date , and returns them to a json object, everything goes well .

What I want to do is add a final property with the average of the prices of all the extracted records

The code I use in the controller is

$resultado = Compras::select("id_compra","nombre_producto","precio","fecha_compra")->where("nota_venta","=","1");

return response()->json($resultado);

The object I want to generate is like the following:

[{id_compra:1, nombre_producto:"producto 1", precio:30,fecha_compra:"2018-08-18"},
{id_compra:2, nombre_producto:"producto 2", precio:45,fecha_compra:"2018-08-18"},
{id_compra:3, nombre_producto:"producto 3", precio:80,fecha_compra:"2018-08-18"},
{id_compra:4, nombre_producto:"producto 4", precio:70,fecha_compra:"2018-08-18"},
{"promedio_precio":56.25}]

Thank you very much for your help

    
asked by Manuel Luna Soto 05.07.2018 в 02:29
source

2 answers

2

One way to do that is to use the avg() method:

$resultado = Compras::select("id_compra","nombre_producto","precio","fecha_compra")->where("nota_venta","=","1");

$promedio = $resultado->avg('precio');

return response()->json([
    'resultado' => $resultado,
    'promedio' => $promedio,
]);

Here is the documentation, Method average () or avg ()

## ADDED ##
There I saw your solution and I did not think it was necessary to have everything in the same collection.
It is not necessary that you make so many steps to unite everything, you can directly do:

$resultado = Compras::select("id_compra","nombre_producto","precio","fecha_compra")
                         ->where("nota_venta","=","1")
                         ->get();

$resultado->put('promedio', $resultado->avg('precio'));

return response()->json($resultado);

I hope my new contribution will help you.

    
answered by 05.07.2018 в 04:31
1

Many thanks to Maru Amallo's response, it helped me to look more in the documentation and can do the following code:

$resultado = Compras::select("id_compra","nombre_producto","precio","fecha_compra")->where("nota_venta","=","1");

$promedio = $resultado->avg('precio');
$collection = collect([["promedio"=>$promedio]]);
$resultado = $resultado->concat($collection);
return response()->json($resultado);

Thanks

    
answered by 05.07.2018 в 16:01