Laravel/LaraCSV - Global Variable in beforeEach

52
February 12, 2019, at 8:20 PM

I have a function in my Controller where I'm trying to export a .csv file using LaraCSV. This is their available documentation: https://github.com/usmanhalalit/laracsv#full-documentation. For whatever reason, I can't seem to use the $doctor variable that I declared earlier in the function into the beforeEach function for LaraCSV. Is anyone aware of how this can be accomplished? Or will I need to perform another where() find from the patient to the doctor?

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');
}
Answer 1

Use php Closure statement like this

$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;
    });
READ ALSO
Cannot get difference between two timestamps

Cannot get difference between two timestamps

I want return the number of dates which have a difference less than 30 minutesThese are the records stored in the database:

54
Parse SOAP web service XML response

Parse SOAP web service XML response

I´m consuming a WS and it gives me data as XMLWhen the response returns to my PHP it came as Object and not as XML

44
How to extract in an array using Simple HTML Dom

How to extract in an array using Simple HTML Dom

I am trying to extract some values parsing html from a websiteWhere are many values with the same tag and when I try to extract them, I got back just "array" word

49
Best way to combine two tables in php [on hold]

Best way to combine two tables in php [on hold]

I'm working on a project where I want to be able to create a weekly calendar and display shifts for that week next to each employee's name

65