Viewing File: /home/ubuntu/route-and-root-backend-base/app/Imports/CountriesImport.php

<?php

namespace App\Imports;

use Illuminate\Support\Collection;

use Maatwebsite\Excel\Concerns\ToCollection;

use App\Models\{ Country };

use App\Helpers\Helper;

use DB, Exception;

class CountriesImport implements ToCollection
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows)
    {
        try {

            DB::beginTransaction();

            foreach($rows as $row) {

                $is_already_exists = Country::where('state', "LIKE", "%" . $row[0] . "%")
                                            ->where('country', "LIKE", "%" . $row[1] . "%")
                                            ->where('country_code', "LIKE", "%" . $row[2] . "%")
                                            ->exists();

                if(!$is_already_exists) {

                    $country = Country::create([
                        'state' => $row[0],
                        'country' => $row[1],
                        'country_code' => $row[2],
                    ]);

                    if(!$country) {

                        throw new Exception(api_error(144), 144);
                    }
                }
            }

            DB::commit();

            return redirect()->route('admin.countries.index')->with('flash_success', tr('countries_exported_success'));  

        } catch(Exception $e) {

            DB::rollback();

            info($e->getMessage());

            return redirect()->back()->with('flash_error' , $e->getMessage());
        }
    }
}
Back to Directory File Manager