这是我的 Laravel Controller 之一中的一些代码,用于生成多个时间表 PDF。它只创建 1 个,我确信这是由于 return 语句造成的,但我如何让它创建所有 PDF?我正在使用 barryvdh/laravel-dompdf。
public function alltimesheets(Request $request)
{
$weeks = Timesheet::where('week_ending', $request->week_ending)->get();
$week_ending = Carbon::parse($request->week_ending)->format('d-m-Y');
foreach($weeks as $hours)
{
$pdf = PDF::loadView('pdf.timesheet', compact('hours', 'week_ending'));
$sheet = $pdf->setPaper('a4', 'landscape');
return $sheet->download($hours->user->name.' - '.$week_ending.'.pdf');
}
}
最佳答案
首先将所有 View html 放入一个变量中,然后将其传递给 PDF。
尝试以下代码:
public function alltimesheets(Request $request)
{
$weeks = Timesheet::where('week_ending', $request->week_ending)->get();
$week_ending = Carbon::parse($request->week_ending)->format('d-m-Y');
$html = '';
foreach($weeks as $hours)
{
$view = view('pdf.timesheet')->with(compact('hours', 'week_ending'));
$html .= $view->render();
}
$pdf = PDF::loadHTML($html);
$sheet = $pdf->setPaper('a4', 'landscape');
return $sheet->download('download.pdf'); // $hours can not be accessed outside foreach. So changed the file name to `download.pdf`.
}
关于php - 使用循环生成多个PDF文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49999146/