4

Can't Download File as CSV

I'm trying to export some data as CSV & every time i try to export data i got this error - Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::header()

I have tried different possible ways but they aren't working

My Function (Controller File)

public function exportd(Request $request)
{
    $fileName = 'data.csv';
    $data = json_decode($request->data);

    $headers = array(
        "Content-type"        => "text/csv",
        "Content-Disposition" => "attachment; filename=$fileName",
        "Pragma"              => "no-cache",
        "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
        "Expires"             => "0"
    );

    $columns = array('Name', 'Gender', 'experrience', 'location', 'Pref Location', 'Salary'
    ...
    );

    $callback = function() use($data, $columns) {
        $file = fopen('php://output', 'w');
        fputcsv($file, $columns);

        foreach ($data as $da) {
            $row['Name']  = $da->name;
            $row['Gender']  = $da->gender;
            $row['experrience']    = $task->experrience;
            $row['Pref Location']  = $task->pref_loc;
            $row['Salary']  = $task->salary;
            ...



                fputcsv($file, array($row['Name'], $row['Gender'],$row['experrience'], $row['location'], $row['Pref Location'], $row['Salary'] 
                ...
                   ));
            }

            fclose($file);
        };

    return Response()->stream($callback, 200, $headers);
}

My Middleware (AuthCheck)

public function handle(Request $request, Closure $next)
{

    if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
        return redirect('auth/login')->with('fail','You must be logged in');
    }

    if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
        return back();
    }
    return $next($request)->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
                          ->header('Pragma','no-cache')
                          ->header('Expires','0');
}
1
  • I suppose you want to add the headers only when $next($request) is an instance of Illuminate\Http\Response (Not sure that the right class though) Commented Apr 29, 2022 at 16:30

2 Answers 2

4

$next($request) is an instance of Symfony\Component\HttpFoundation\StreamedResponse in your scenario.

StreamedResponse does not support ->header(...). If you want to preserve your ->header(...) call, you must verify that the response is an instance of Illuminate\Http\Response


public function handle(Request $request, Closure $next)
{

    if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
        return redirect('auth/login')->with('fail','You must be logged in');
    }

    if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
        return back();
    }

    $response = $next($request);

    if($response instanceof \Illuminate\Http\Response) {
        return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
                          ->header('Pragma','no-cache')
                          ->header('Expires','0');
    }

    return $response;

}

Sign up to request clarification or add additional context in comments.

8 Comments

An alternative worth to mention is that headers can be configured at your HTTP server level (nginx / Apache)
getting this error - This site can’t be reached ERR_INVALID_RESPONSE
ERR_INVALID_RESPONSE is usually a DNS issue. Are you certain this error come from the if condition ?
when i paste ur code i got this issue - ERR_INVALID_RESPONSE The webpage at http://127.0.0.1:8000/exportd might be temporarily down or it may have moved permanently to a new web address.
What if you don't use the middleware ?
|
0
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $request->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
        $request->header('Access-Control-Allow-Origin', '*'); 
        return $response->prepare($request);
 
    }
}

Use above snip code. it has prepare() function in response object that you should add header on it and return it to the handle function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.