我正在使用maatwebsite/excel库创建excel文件,然后下载我的文件.

In my controller I do like this:

  public function todas()
    {
        $input = Input::all();

        if(isset($input['todos'])&&($input['todos']!=0))
        {
            set_time_limit(0);
            $datainicio = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('periodo_inicio'); 
            $datafinal  = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('periodo_fim');
            $mes  = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('mes_referencia'); 

            $horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
                                 ->whereBetween('data', array($datainicio, $datafinal))
                                 ->whereNull('deleted_at')
                                 ->orderBy('cod_funcionario')
                                 ->orderBy('data', 'ASC')
                                 ->get();

            $horarios = reset($horarioQuery);
            
            $count  = count($horarios);

            if($horarios==null)
                return Redirect::route('relatorios.todas')->withErrors(['não existem marcações para este período']);

            $funcionarios = $this->funcionario->all();

            $datainicio  = Carbon::createFromFormat('Y-m-d H:i:s', $datainicio); 
            $datafinal   = Carbon::createFromFormat('Y-m-d H:i:s', $datafinal);

            $nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
            $this->horario->allToExcel($nome, $horarios);

            return View::make('relatorios.todashow', compact('funcionarios', 'datainicio', 'datafinal', 'horarios', 'count', 'nome'));
        }
        else
        {
            return Redirect::route('relatorios.todas')->withErrors(['Selecione um período!']);
        }
    }

That is my function to generate excel file :

public static function allToExcel($nome, $horarios)
    {   
            Excel::create($nome , function ($excel) use ($horarios) {

            $excel->sheet('Marcações', function ($sheet) use ($horarios) {

                $sheet->row(1, array(

                            'Unidade',
                            'Nome',
                            'Função',
                            'Data',
                            'Hora Faturada',
                            'Hora Contratada',
                            'Horas Trabalhadas',
                            'Horas Extras',
                            'Tempo Exposicao',
                            'Atividade',
                            'Item Contabil',
                            'Observacoes'
                        ));

                $sheet->row(1, function($row) {
                    $row->setBackground('#2A8005');
                    $row->setFontColor('#ffffff');
                    $row->setFontWeight('bold');
                });

                $i = 2;
                foreach ($horarios as $horario) {
                        
                        if($horario->funcionario->funcao_qt != null)
                            $funcao = $horario->funcionario->funcao_qt;
                        else   
                            $funcao = $horario->funcionario->funcao_a5;
        
                        $sheet->row($i, array(
                            $horario->unidade,
                            $horario->funcionario->nome,
                            $funcao,
                            $horario->data->format('d/m/Y'),
                            $horario->hora_faturada->format('H:i'),
                            $horario->hora_contratada,
                            $horario->getWorkedHours()->format('H:i'),
                            $horario->getExtraHours()->format('H:i'),
                            $horario->tempo_exposicao ?: "-",
                            $horario->atividade,
                            $horario->item_contabil->CTD_DESC01,
                            $horario->observacoes
                        ));
                        if($i % 2 != 0)
                        {
                        $sheet->row($i, function($row) {
                            $row->setBackground('#D1D1D1');
                            });
                        }    
                
                        $i++;
                    }
            });

            })->download('xls');
    }

但下载excel文件后,我无法重定向到路由或视图,我还try 使用:

路由:

Route::post('relatorios/todas', array('as' => 'relatorios.todas', 'after' => 'voltar', 'uses' => 'ReportsController@todas'));

过滤器:

Route::filter('voltar', function()
{
    return Redirect::back()->with('message', '<p class="bg-success"><b>Relatório gerado com sucesso</b></p>');
});

但是无论如何它都不起作用,有没有其他方法可以在下载我的文件后进行重定向?

推荐答案

这是不可能做到的.问题是,如果向用户浏览器发送下载指令,实际上就是在发送响应,并且只能返回一个响应.

您可以做的是,首先将您的用户重定向到"最终"页面,然后在该页面中开始下载.代码应该类似于:

Session::flash('download.in.the.next.request', 'filetodownload.pdf');

return Redirect::to('/whatever/page');

然后,在您的新页面中,您将有一些选项:

So you can in your layout do something like:

<html>
  <head>
      @if(Session::has('download.in.the.next.request'))
         <meta http-equiv="refresh" content="5;url={{ Session::get('download.in.the.next.request') }}">
      @endif
   <head>

   <body>
      ...
   </body>
</html>

Also, take a look at this answer: PHP generate file for download then redirect

Laravel相关问答推荐

Inertia React中的错误文件上传更新

AJAX响应中未定义的全名

如何在Vite和Rollup中完全禁用分块?

Laravel PHP 框架的新手. /以外的路由不起作用

Laravel 5.1 如何在Blade 文件上使用 {{ old('') }} 助手进行无线电输入

在集合 laravel 中使用查询范围

Laravel - 如何恢复本地存储符号链接并刷新

Laravel - 超过 PHP 最大上传大小限制时验证文件大小

Laravel 5.5 类型错误:传递给 Illuminate\Auth\EloquentUserProvider::validateCredentials() 的参数 1 必须是实例

SQLSTATE [42000]:语法错误或访问冲突:1066 Not unique table/alias on relationship

Http请求多浏览器的烦恼

如何将对象(模型类型对象)插入到 Laravel 中特定索引号的集合对象中?

Laravel - 语法错误,文件意外结束

是否可以将路由参数传递给 Laravel 中的控制器构造函数?

今天之前的 Laravel 规则......怎么办

Laravel 用户能力

如何使 Laravel (Blade) 文本字段只读

如何在脚本文件中使用 Laravel Blade?

如何在不要求用户登录 Laravel 的情况下验证Electron邮件

使用 Carbon 将小时转换为 PM 和 AM