Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return variable from within Laravel Excel Import

Code Below, basic example, but I want to return errors (see commented out if statement after the import ). How would I pass variables from the 'import' class back to the controller?

Controller:

public function resultsImport(Request $request)
{
    //validate the xls file
    $this->validate($request, array('student_results_import_file' => 'required'));

    if($request->hasFile('student_results_import_file')){
        $extension = File::extension($request->student_results_import_file->getClientOriginalName());
        if ($extension == "xlsx" || $extension == "xls" || $extension == "csv") {

            Excel::import(new StudentResultsImport, $request->file('student_results_import_file'));
// if $ignore_count>0 --> do stuff
            return redirect('/baadmin/students')->with('flash_message', ['success','Results Imported Successfully','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" imported successfully!']);
        } else {
            return redirect('/baadmin/students')->with('flash_message', ['error','Results Import Failed','Student file "'. $request->student_results_import_file->getClientOriginalName() .'" import failed. File is a '. $extension .' file. Please upload a valid xls/csv file.']);
        }
    }
}

Import

public function collection(Collection $rows)
{
    set_time_limit(300);
    $ignore_count = 0;

    foreach ($rows as $row) {
        if ($row[8] != '') {
        //import
        }
        else {
        $ignore_count++;
        //$ignore_count is just a simple example, ultimately would probably have an array of the various errors detected on the various rows
        }
    }
}
like image 544
SupaMonkey Avatar asked Aug 15 '19 10:08

SupaMonkey


1 Answers

Managed to find the appropriate answer in the documentation, referring to 'Getters': https://docs.laravel-excel.com/3.1/architecture/objects.html#getters

eg:

namespace App\Imports;

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
    private $rows = 0;

    public function model(array $row)
    {
        ++$this->rows;

        return new User([
            'name' => $row[0],
        ]);
    }

    public function getRowCount(): int
    {
        return $this->rows;
    }
}

After doing the import, we can request the state with the getter.

$import = new UsersImport;
Excel::import($import, 'users.xlsx');

dd('Row count: ' . $import->getRowCount()); 
like image 194
SupaMonkey Avatar answered Nov 18 '22 07:11

SupaMonkey