Sydney Loteria
Sydney Loteria

Reputation: 10471

Access variable outside of Excel::load in Laravel

I would like to ask if how can I access the error message variable when I execute the a foreach loop inside the Excel::load function which reads the csv file that I uploaded so that I can return it via the Response::json();

Here's my code:

$errorMessage['error'] = [];

        if($request->hasFile('file')){
            if($request->file('file')->getClientOriginalExtension() != "csv"){
                $errorMessage['error'][] = "File should be in csv format";
            }
            else {

                $fileName = $request->file('file')->getClientOriginalName().".csv";
                $destination = base_path().'/storage/excel/imports';
                $request->file('file')->move($destination, $fileName);

                $csvFile = base_path().'/storage/excel/imports/'.$fileName;

                $demographics = $request->get('demographics');

                \Excel::load($csvFile, function($reader) use($demographics,$errorMessage) {
                        if($demographics == "region"){
                            foreach($reader->get()->toArray() as $data){
                                $region = Region::whereRaw("LCASE(`short_name`) = ?", array(strtolower($data['region_name'])))->first();
                                if($region){
                                    $regionData = Region::find($region->id);
                                    $regionData->total_number_of_provinces = $data['total_provinces'];
                                    $regionData->total_number_of_cities_municipalities = $data['total_cities_and_municipalities'];
                                    $regionData->save();

                                }
                                else {
                                    $errorMessage['error'][] = $data['region_name'] . " is not existing in the database";
                                }
                            }
                        }

                });
            }
        }
        else {
            $errorMessage['error'][] = "Please specify a file";
        }

        return \Response::json($errorMessage);

Upvotes: 0

Views: 1817

Answers (2)

Mahesh Yadav
Mahesh Yadav

Reputation: 2684

   $fileName = md5(time()) .'.'.$request->file('file')->getClientOriginalExtension();
   $sheet_id  = $request->session()->get('sheet_id');
   $excel=Excel::load(public_path('/uploads/importsheet/'.$fileName),function ($reader)use ($sheet_id) {

        $reader->each(function($sheet) use ($sheet_id) {                                                
            $headings = $sheet->keys()->toArray();              
            for($i=0; $i<count($headings); $i++){
                $sheet_id = DB::table('import_sheets_attributes')->insertGetId(
                    [
                        'import_sheets_id' => $sheet_id,
                        'attribute'  => $headings[$i],
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
            }        
        });
    });

Hope the above sample code will help.

Upvotes: 0

Loek
Loek

Reputation: 4135

Bit smelly, but you can declare it a class property.

/**
* @var array
*/
protected $errorMessage;

public function doStuff()
{
    // ...

    \Excel::load($file, function($reader) use ($demographics) {

        // ...

        $this->errormessage['error'][] = $data['region_name'];
    });

    // ...

    return \Response::json($this->errorMessage);
}

Note

You can also pass $errorMessage by reference, which a lot of people think is the better choice (you're using a throw-away function after all).

\Excel::load($file, function($reader) use ($demographics, &$errorMessage)

I don't like to do this however, because in my opinion it's less readable what I meant to do. You can choose one of either picks though!

Useful and short explanation: http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/

Upvotes: 1

Related Questions