PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 4, 2022

[FIXED] How to get specific columns in Laravel [Maatwebsite/Laravel-Excel]

 October 04, 2022     excel, laravel, php, phpexcel, phpoffice     No comments   

Issue

the file i am importing has thousands of records which is causing my network to get slow. i want to read only those columns that i need, before inserting it into database. When file is processed , it should first search those columns not the whole file, and fetch the rows of those columns

Excel::load($path, function($reader) {

//Getting headers using this


       $headers = $reader->first()->keys()->toArray();

//This is the array of required columns

       $headings = array('registrant_name','registrant_address','registrant_phone','registrant_zip','registrant_email','registrant_country','registrant_state','registrant_city');


});

Data insertion after file read.

 if($data->count() > 0)
             {
              foreach($data->toArray() as $value)
              {
                $insert[] = array(
                 'registrant_name'  => $value['registrant_name'],
                 'registrant_address'   => $value['registrant_address'],
                 'registrant_phone'   => $value['registrant_phone'],
                 'registrant_zip'   => $value['registrant_zip'],
                 'registrant_email'   => $value['registrant_email'],
                 'registrant_country'   => $value['registrant_country'],
                 'registrant_state'   => $value['registrant_state'],
                 'registrant_city'   => $value['registrant_city']

                );                
               }
              }


      if(!empty($insert))
      {
       DB::table('customers')->insert($insert);
      }    

Solution

In collections, you can check the method only documentation

i.e.

$headers = $reader->first()->only(['registrant_name','registrant_address','registrant_phone','registrant_zip','registrant_email','registrant_country','registrant_state','registrant_city']);

You might also use chunk, to insert the data in smaller collections than in one big.

Could you update the post with the App\Import class in order to help you more.



Answered By - Nikolas
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing