问题
Here is some code in one of my Laravel controllers to generate multiple timesheet PDF's. It only creates 1 and Im sure its due to the return statement but how do i get it to create all PDF's? I'm using 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');
}
}
回答1:
First get all views html in one variable and then pass it to PDF.
Try the following code:
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`.
}
回答2:
Referring to the answer above by Himashu. I would like to add some code which can download the multiple pdf at a specific location. This creates a separate pdf for each file.
$invoices = Invoices::where('user_id', '=', $user_id)->get();
foreach($invoices as $key => $invoice)
{
$user_details = Users::where('id',$invoice->user_id)->first();
$html = '';
$view = view('pdf.invoice_compact')->with(compact('user_details','invoice'));
$html .= $view->render();
PDF::loadHTML($html)->save(public_path().'/bulk_invoices/'.$invoice->id.'.pdf');
}
来源:https://stackoverflow.com/questions/49999146/generate-multiple-pdf-documents-with-loop