Skip to content

Instantly share code, notes, and snippets.

@acidjazz
Last active January 6, 2022 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acidjazz/71c7f40d3f596ddd4580a353e5bdb986 to your computer and use it in GitHub Desktop.
Save acidjazz/71c7f40d3f596ddd4580a353e5bdb986 to your computer and use it in GitHub Desktop.
smart table export service
<?php
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @param Request $request
* @return Response|JsonResponse
* @throws AuthorizationException
*/
public function index(Request $request): Response|JsonResponse|StreamedResponse
{
$this
...
->option('export', 'nullable|in:true')
->option('cols', 'nullable')
->verify();
$this->authorize('viewAny', auth()->user());
$query = User
::when(
$request->search,
fn($q) => $q->where('name', 'LIKE', "%$request->search%")
)
...
);
if ($request->export === 'true' && $request->cols) {
return response()->stream(
SmartTable::callback($request->cols, $query),
200,
SmartTable::headers('users')
);
}
return $this->render($this->paginate($query, $request->perpage ?? 10));
}
<?php
namespace App\Services;
use Closure;
use Illuminate\Database\Eloquent\Builder;
class SmartTable
{
public static function callback(string $cols, Builder $query): Closure
{
return function () use ($cols, $query) {
$labels = array_map(fn($c) => substr($c, strpos($c, ':') + 1), explode(',', $cols));
$fields = array_map(fn($c) => strtok($c, ':'), explode(',', $cols));
$file = fopen('php://output', 'w');
fputcsv($file, $labels);
foreach ($query->get($fields) as $row) {
fputcsv($file, $row->only($fields));
}
fclose($file);
};
}
public static function headers(string $name): array
{
$file = $name . '-' . date(DATE_W3C);
return [
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename=$file.csv",
'Pragma' => 'no-cache',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Expires' => '0',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment