0

Hello there

Hope you will be doing well.I want to redirect to a route after file download but as we know that return only works once in a controller method how i can achieve this with laravel 5.7.I have to set a session and display it when data exported in txt file.I want this with post method. Every thing is fine but redirect is not working;

Controller Method

public function exportTxtProcess(Request $request)
{
    $table = $request->tblExportSelect;

    $destinationPath = public_path('/');

    $result;

    $outputs = DB::select("SELECT * FROM $table");

    $today = date("Y-m-d");
    $fileName = $table . "-" . $today;
    $fp = fopen($destinationPath . "$fileName.txt", "wb");

    foreach ($outputs as $output) {
        $output = (array)$output;

        @array_shift($output);

        $removeUserId = @$output['user_id'];
        $created_at = @$output['created_at'];
        $updated_at = @$output['updated_at'];

        if (($key = array_search($removeUserId, $output)) !== false) {
            unset($output[$key]);
        }
        if (($key1 = array_search($created_at, $output))) {

            unset($output[$key1]);
        }

        if (($key2 = array_search($updated_at, $output))) {

            unset($output[$key2]);
        }

        if (is_null($created_at) OR $created_at == '') {
            unset($output['created_at']);
        }

        if (is_null($updated_at) OR $updated_at == '') {
            unset($output['updated_at']);
        }


        $netResult = $this->getTableFields($table, $output);

        fwrite($fp, $netResult);

    }

    $result = fclose($fp);


    if ($result) {
        $pathToFile = $destinationPath . "$fileName.txt";

        $redirect = redirect()->back();
        $sess = Session::flash('success', 'Table exported successfully');
        return response()->download($pathToFile)->deleteFileAfterSend(true);


    }

}

Thank in advance

Moshiur
  • 659
  • 6
  • 22
Sadam Hussain
  • 23
  • 1
  • 5
  • Does this answer your question? [How do I redirect after download in Laravel?](https://stackoverflow.com/questions/25624927/how-do-i-redirect-after-download-in-laravel) – Foued MOUSSI Feb 12 '20 at 07:04

1 Answers1

0

You can only have 1 response, so it's impossible to instruct a double return. What you could do, is set the filename you wish to have downloaded in a session variable, then redirect back to whatever page. Within the redirected page, you could flash your message, along with having an automatic download of the file.

Here is some threads on the topic:

How do I redirect after download in Laravel?

PHP generate file for download then redirect

Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39