Подтвердить что ты не робот

Как перенаправить после загрузки в Laravel?

Я использую библиотеку maatwebsite/excel для создания файлов excel, а затем загружаю файл

в моем контроллере мне это нравится:

  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!']);
        }
    }

это моя функция для генерации файла excel:

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 я не могу перенаправить маршрут или просмотр, и я также попытался использовать:

маршруты:

Route::post('relatorios/todas', array('as' => 'relatorios.todas', 'after' => 'voltar', 'uses' => '[email protected]'));

Фильтр:

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

но все равно не работал, есть другой способ перенаправления после загрузки моего файла??!

спасибо заранее!

4b9b3361

Ответ 1

Это невозможно. Проблема в том, что если вы отправляете инструкцию загрузки в пользовательский браузер, вы, по сути, отправляете ответ, и вы можете отправить только один ответ.

Что вы можете сделать, так это сначала перенаправить пользователя на "последнюю" страницу и на этой странице начать загрузку. Код будет примерно таким:

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

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

Затем на вашей новой странице у вас есть несколько вариантов:

Итак, вы можете в своем расположении сделать что-то вроде:

<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>

Кроме того, взгляните на этот ответ: PHP генерирует файл для скачивания, затем перенаправляет

Ответ 2

который работал

Я отказался от использования ajax и просто попробовал с маршрутами

Route::get('relatorios/exportar/{cod}', array('as' => 'relatorios.exportar', 'uses' => '[email protected]'));

мой контроллер

 public function exportar($cod)
    {   
        set_time_limit(0);
        $datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio'); 
        $datafinal  = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
        $mes  = DB::table('tb_periodo')->where('cod', $cod)->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);

        $nome = 'Marcações'.$mes.'-'.Carbon::now()->year;

        $this->horario->allToExcel($nome, $horarios);
    }

Вид:

 {{ link_to_route('relatorios.exportar', 'Exportar para excel', array($cod), array('class' => 'btn btn-success')) }}

который решил для меня, потому что не загружайте другую страницу и загружайте правильный файл. спасибо для справки!!