leftJoin('StatoProdotto as sp', function ($join) { $join->on('Article.idStatoProdotto', '=', 'sp.idStatoProdotto') ->where('sp.dataOra', '=', DB::raw('(SELECT MAX(dataOra) FROM StatoProdotto WHERE idStatoProdotto = sp.idStatoProdotto)')); }) ->whereIn('sp.descrizione', ['In commercio', 'In prevendita', 'Prossima uscita']) ->selectRaw('Article.idArticolo, SUM(Ordine.qta) as totaleVenduto') ->groupBy('Article.idArticolo') ->take(10) ->get(); $filename = 'articoli_venduti_' . date('Y-m-d') . '.csv'; $response = new Response(); $response->headers->set('Content-Type', 'text/csv'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"'); $csvContent = "IdArticolo,TotaleVenduto\n"; foreach ($articoliVenduti as $articoloVenduto) { $csvContent .= $articoloVenduto->idArticolo . ',' . $articoloVenduto->totaleVenduto . "\n"; } $response->setContent($csvContent); return $response; } catch (\Exception $e) { return new Response('Error exporting articles: ' . $e->getMessage(), 500); } } }