@@ -138,7 +138,6 @@ public function downloadCsv(): StreamedResponse
138138 $ headers = array_values ($ this ->viewAttributes );
139139 $ handle = fopen ('php://memory ' , 'w+ ' );
140140
141- // Write data to the memory stream
142141 fputcsv ($ handle , $ headers );
143142 foreach ($ data as $ item ) {
144143 $ row = [];
@@ -148,15 +147,45 @@ public function downloadCsv(): StreamedResponse
148147 fputcsv ($ handle , $ row );
149148 }
150149
151- // Rewind the memory stream to the beginning and capture the CSV content
152150 rewind ($ handle );
153151 $ csvContent = stream_get_contents ($ handle );
154152 fclose ($ handle );
155153
156- // Stream the CSV content as a download
154+ $ exportName = $ this ->generateExportFilename ();
155+
157156 return response ()->streamDownload (function () use ($ csvContent ) {
158157 echo $ csvContent ;
159- }, 'data.csv ' , ['Content-Type ' => 'text/csv ' ]);
158+ }, $ exportName , ['Content-Type ' => 'text/csv ' ]);
159+ }
160+
161+ protected function generateExportFilename (): string
162+ {
163+ $ modelName = class_basename ($ this ->model );
164+ $ fileName = $ modelName ;
165+
166+ if (!empty ($ this ->filter )) {
167+ $ filterInfo = $ this ->filterColumn !== 'all '
168+ ? "{$ this ->filterColumn }- {$ this ->filter }"
169+ : "filter- {$ this ->filter }" ;
170+
171+ $ filterInfo = preg_replace ('/[^a-zA-Z0-9_-]/ ' , '_ ' , $ filterInfo );
172+ $ fileName .= "- {$ filterInfo }" ;
173+ }
174+
175+ if (!empty ($ this ->sort )) {
176+ $ sortInfo = [];
177+ foreach ($ this ->sort as $ column => $ direction ) {
178+ $ sortInfo [] = "{$ column }- {$ direction }" ;
179+ }
180+ if (!empty ($ sortInfo )) {
181+ $ fileName .= "-sort- " . implode ('- ' , $ sortInfo );
182+ }
183+ }
184+
185+ $ fileName .= "- " . date ('Y-m-d ' );
186+ $ fileName = preg_replace ('/[^a-zA-Z0-9_-]/ ' , '_ ' , $ fileName );
187+
188+ return "{$ fileName }.csv " ;
160189 }
161190
162191 protected function getData (bool $ paginate = true , bool $ highlightMatches = true , bool $ applyFormats = true )
0 commit comments