Laravel / LaraCSV-beforeEach中的全局变量

时间:2019-02-11 16:51:01

标签: php laravel

我的控制器中有一个函数,我正在尝试使用LaraCSV导出.csv文件。这是他们的可用文档:https://github.com/usmanhalalit/laracsv#full-documentation。无论出于何种原因,我似乎都无法将在函数中先前声明的$doctor变量用于LaraCSV的beforeEach函数中。有谁知道如何做到这一点?还是我需要从患者到医生再进行一次where()查找?

public function doctorCSV($id) {
    $csvExporter = new \Laracsv\Export();
    $doctor = Doctor::findOrFail($id);
    $scripts = $doctor->scripts()->get();

    $csvExporter->beforeEach(function ($script) {
        $patients = Patient::all();
        $patient = $patients->where('id', $script->patient_id)->first();
        $script->patient = $patient->full_name;
        $script->doctor = $doctor->full_name;
    });

    return $csvExporter
        ->build($scripts, [
            'prescribe_date' => 'Prescribe Date',
            'doctor' => 'Doctor',
            'patient' => 'Patient',
            'status' => 'Status'
        ])
        ->download('Report - ' . $doctor->full_name . ' - ' . date('m-d-Y') . '.csv');
}

1 个答案:

答案 0 :(得分:1)

使用php Closure这样的语句

$csvExporter->beforeEach(function ($script) use($doctor) { // here
        $patients = Patient::all();
        $patient = $patients->where('id', $script->patient_id)->first();
        $script->patient = $patient->full_name;
        $script->doctor = $doctor->full_name;
    });