Can't import excel data in Laravel 8. am new to it

Viewed 682

**Am new to laravel8 trying to import data from excel sheet to the database, here is my code in the import class its not passing not giving any error. so the database has relationship am trying to import the data and make sure the relationships are considered so that l shouldn't have any problems **


   <?php
   
   namespace App\Imports;
   
   use Illuminate\Support\Collection;
   use Maatwebsite\Excel\Concerns\ToCollection;
   use App\Models\District;
   use App\Models\Organisation;
   use App\Models\FocalPerson;
   use App\Models\Ta;
   use App\Models\Location;
   use App\Models\Service;
   use App\Models\Category;
   use App\Models\Type;
   
   
   
   
   class InformationImport implements ToCollection
   {
       /**
       * @param array $row
       *
       * @return \Illuminate\Database\Eloquent\Model|null
       */
       public function collection(Collection $rows)
       {
           foreach ($rows as $row) 
           {
               $instance_id = $row[1];
               $organisation_name = $row[2];
               $service_provider = $row[3];
               $catchment_area = $row[4];
               $organisation_type = $row[5];
               $district_name = $row[6];
               $organisation_web = $row[7];
               $primary_name = $row[8];
               $primary_title = $row[9];
               $primary_number = $row[10];
               $primary_email = $row[11];
               $secondary_name = $row[12];
               $secondary_number = $row[13];
               $secondary_title = $row[14];
               $secondary_email = $row[15];
               $services_name = $row[16];
               $location = explode(',',$row[17],2);
               return $location;
               $location_altitude = $row[18];
               $location_accuracy = $row[19];
               $comments_distance = $row[20];
               $data_comments = $row[21];
   
              $ta = Ta::where('name','like','%'.$row[4] .'%')->whereHas('district', 
               function($query) use($district_name){
                  $query->where('name','like','%'.$district_name .'%');
               })->get();
               if(!$ta){
                   $district = District::firstOrCreate([
                       'name' => $row[6]
                   ]);
                   $ta = new Ta;
                   $ta->name = $row[4];
                   $district->tas()->save($ta);
               }
               $gvh = Gvh::firstOrCreate([
                   'name' => 'unknown',
                   'ta_id' => $ta->id
               ]);
               $location = Location::firstOrCreate([
                   'latitude'=>$location,
                   'longitude'=>$location,
                   'gvh_id'=> $gvh->id
               ]);
               $service = Service::firstOrCreate([
                   'name'=>$services_name
               ]);
               $category = Category::firstOrCreate([
                   'name'=>'unknown'
               ]);
               $type = Type::firstOrCreate([
                   'name'=>$organisation_type
               ]);
               $organisation = Organisation::firstOrCreate([
                    'name'=> $organisation_name,
                    'location_id' => $location->id,
                    'organisation_type_id' => $type->id,
                    'organisation_category_id' => $category->id
               ]); 
               $focalperson =FocalPerson::firstOrCreate([
                   'title'=>  $primary_title, $secondary_title,
                   'name' => $primary_name,$secondary_name,
                   'phonenumber'=>$primary_number,$secondary_number,
                   'email'=> $primary_email, $secondary_email
               ]);
           }
       }
       
   }

**below is my controller class. in the controller that's the code l have because it wasn't bringing anything l had to write it in that way and see if it will be able to output the messages **


 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\InformationImport;
use Maatwebsite\Excel\Facades\Excel;

class InformationController extends Controller
{
 
 public function import(Request $request) 
 {
     //Excel::import(new InformationImport, $request->file); 
     //return response()->json(['message' => 'Your data imported successfully !'], 200);
     if ($request->ajax()) {

         try {
 
             Excel::import(new InformationImport, $request->file);
 
             return response()->json(['message' => 'Your data imported successfully !'], 200);
 
         } catch (ValidationException $ex) {
 
             $failures = $ex->failures();
             foreach ($failures as $failure) {
                 return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
             }
 
         }
 
     }
     return response()->json(['message' => 'Something went wrong !'], 500);
 }
 
}
2 Answers
   public function import(Request $request) 
   {
       ini_set('max_execution_time', -1);
       ini_set('memory_limit ', -1);
      
       if ($request->ajax()) {

          try {
             $file_content = $request->file('excel');
             $file_name = time() . '.xlsx';

             Storage::disk('local')->putFileAs('public', $file_content, $file_name);
             $url = "/app/public/" . $file_name;
             $path = storage_path() . $url;
             Excel::import(new InformationImport, $path);
 
             return response()->json(['message' => 'Your data imported successfully !'], 200);
 
         } catch (ValidationException $ex) {
 
             $failures = $ex->failures();
             foreach ($failures as $failure) {
                 return response()->json(['message' => 'Row - ' . $failure->row() . ', ' . $failure->errors()[0]], 500);
             }
         }
      }
      return response()->json(['message' => 'Something went wrong !'], 500);
     }

This is sample and runnable code. Please refer

In Your Controller 


public function import(Request $request){

        $this->validate($request,[
            'file'=> 'required|mimes:xlsx,csv'
        ]);

        try{
            Excel::import(new CannedResponseImport,request()->file('file'));
             
            return back()
                ->withSuccess('Data imported successfully.');
        }catch(\Exception $ex){
            return back()
                ->withError('Someting went wrong please try again.');
        } 
    }

In your Import

<?php

namespace App\Imports;

use App\Models\CannedResponses; 

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Validator;  

class CannedResponseImport implements ToCollection,WithHeadingRow 
{
     
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function collection(Collection $rows)
    {  
       
        foreach ($rows as $row) { 
           
            if($row->filter()->isNotEmpty()){  
                if(!empty($row['business_type_id']) && !empty($row['brand_id']) && !empty($row['contact_reason_id'])
                    && !empty($row['contact_sub_reason_id']) && !empty($row['personality_type_id']) && !empty($row['response_segment_id'])
                    && !empty($row['response_tone_id']) && !empty($row['nature_conversation_id']) && !empty($row['canned_response'])
                ){ 
                    $id = CannedResponses::insertGetId([
                        'business_type_id'      => $row['business_type_id'],
                        'brand_id'              => $row['brand_id'],
                        'contact_reason_id'     => $row['contact_reason_id'], 
                        'contact_sub_reason_id' => $row['contact_sub_reason_id'], 
                        'nature_conversation_id' => $row['nature_conversation_id'], 
                        'personality_type_id'   => $row['personality_type_id'],
                        'response_segment_id'   => $row['response_segment_id'],
                        'response_tone_id'      => $row['response_tone_id'],
                        'message'               => $row['canned_response']
                    ]); 
                   
                }
            } 
        }  
    } 
}

Related