Laravel、Livewire 和 DOMPDF

问题描述 投票:0回答:1

我有一个非常简单的 Livewire 组件:

<?php

namespace App\Http\Livewire;

use PDF;
use Livewire\Component;

use App\Models\Employee;

class Employees extends Component{

public $employees;

public function mount()
{
    $this->employees = Employee::all()->toArray();
}

public function createPDF()
{
    $this->employees = Employee::all()->toArray();
    // dd($this->employees);
    $pdf = PDF::loadView('livewire.employees', $this->employees);
    return $pdf->download('pdf_file.pdf');
}

public function render()
{
    return view('livewire.employees');
}

}

还有一个非常简单的刀片文件,我在其中呈现单击按钮时要打印的员工姓名。

<div class="container mx-auto">
  @foreach ($employees as $e)
    <h2>{{ $e['name'] }}</h2>
  @endforeach
  <button wire:click="createPDF" class="mt-8 bg-black text-white px-4 py-2 rounded">PDF</button>
</div>

问题是我得到了 foreach 循环内的变量“未定义的变量 $employees”。

laravel laravel-livewire dompdf
1个回答
0
投票

您没有在 PDF 调用中设置变量,因此该变量不存在。

简单改变

$pdf = PDF::loadView('livewire.employees', $this->employees);

$pdf = PDF::loadView('livewire.employees', ['employees' => $this->employees]);

附注我不太明白为什么每次单击 PDF 生成按钮时都会获取员工。您已经将其设置在安装中,因此它应该已经设置。每次重新获取都相当慢。

© www.soinside.com 2019 - 2024. All rights reserved.