@@ -138,7 +138,6 @@ public function downloadCsv(): StreamedResponse
138
138
$ headers = array_values ($ this ->viewAttributes );
139
139
$ handle = fopen ('php://memory ' , 'w+ ' );
140
140
141
- // Write data to the memory stream
142
141
fputcsv ($ handle , $ headers );
143
142
foreach ($ data as $ item ) {
144
143
$ row = [];
@@ -148,15 +147,45 @@ public function downloadCsv(): StreamedResponse
148
147
fputcsv ($ handle , $ row );
149
148
}
150
149
151
- // Rewind the memory stream to the beginning and capture the CSV content
152
150
rewind ($ handle );
153
151
$ csvContent = stream_get_contents ($ handle );
154
152
fclose ($ handle );
155
153
156
- // Stream the CSV content as a download
154
+ $ exportName = $ this ->generateExportFilename ();
155
+
157
156
return response ()->streamDownload (function () use ($ csvContent ) {
158
157
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 " ;
160
189
}
161
190
162
191
protected function getData (bool $ paginate = true , bool $ highlightMatches = true , bool $ applyFormats = true )
0 commit comments