Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lifesound's avatar

Datatables data as excel in case all data

I have a complex situation

I have data tables ( Front End rendered ) using server-side: true

so the data comes to the front end using Yajra Datatables

everything works fine Until I wanted to download ( All ) data as excel in that case, the front end should load ( ALL ) the data and then click export excel to get the file But Loading all data to the front end is impractical.

I should use Yajra Datatables completely server-side but that was what I did

to get around that I made a middleware to check if the length of data == '-1' ( ALL Data ) so I should respond with the CSV file

    public function handle(Request $request, Closure $next)
    {
        if ($request->ajax()) {
            $length = $request->query('length');

            if ($length == "-1") {
                $response = $next($request);
               // Here I should do something
                return $response;
            }

        }
        return $next($request);
    }
}

But the structure of Yajra data is not suitable

any idea?

0 likes
1 reply
lifesound's avatar

I have come out to the difficult part


    public function handle(Request $request, Closure $next)
    {
        if ($request->ajax()) {
            $length = $request->query('length');
            if ($length == "-1") {
                $response = $next($request);
                // dd($response->original);
                $headers = array(
                    "Content-type" => "text/csv",
                    "Content-Disposition" => "attachment; filename=\"data.csv\"",
                    "Pragma" => "no-cache",
                    "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
                    "Expires" => "0"
                );

                $callback = function () use ($response) {
                    $out = fopen("php://output", 'w');
                    fputcsv($out, array_keys($response->original['data'][0]), "\t");
                    foreach ($response->original['data'] as $data) {
                        // dd(array_values($data));
                        fputcsv($out, array_values($data), "\t");
                    }
                    fclose($out);
                };

                return response()->stream($callback, 200, $headers);
            }
        }
        return $next($request);
    }

I have played with the data until I get the file BUT the file can not be downloaded through ajax request?

could I redirect to get the file ??

Please or to participate in this conversation.