使用带有 laravel 的 maatwebsite 查询导出 excel

export excel with a query using maatwebsite with laravel

您好,我是使用 maatwebsite 的新手,已经阅读了文档但找不到它,有人可以给我一个关于使用 maatwebsite 导出 excel 后执行查询的想法吗?这是我的代码:

public function export()
{
    Excel::download(new KodePosExport, 'KodePos.xlsx');
    KodePos::query()->truncate();
    return redirect('/')->with('success', 'All good!');
}

它能够重定向到我想要的页面并截断数据但不导出 excel,我该怎么做?谢谢

如果使用此函数导出 excel 工作正常,但不包含查询

public function export()
{
    return Excel::download(new KodePosExport, 'KodePos.xlsx');
    //KodePos::query()->truncate();
    // return redirect('/')->with('success', 'All good!');
}
$download = Export::download(...);

KodePos::query()->truncate();

return $download;

我可能会在这里提出两个解决方案;

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware and your web server is using FastCGI, the terminate method will automatically be called after the response is sent to the browser.

  • 创建一个异步作业并在下载过程之前延迟触发它(您的队列驱动程序不应该 syncredis 是一个很好的选择)
class KudeposTruncater extends Job implements ShouldQueue
{
    use InteractsWithQueue;
    
    public function handle()
    {
        KodePos::query()->truncate();
    }
}
\Queue::later(15, new KudeposTruncater());

return Excel::download(new KodePosExport, 'KodePos.xlsx');