Import the CSV file into the Laravel controller and paste the data into two tables

So, I have a complete noob for Laravel and have tried something here. I want to import a CSV file into two tables, I have a table called lists, which will get the list name and client_id .

Then I have a table called clients, which will get the contact number of the last name, as well as client_id and list_id .

What I want to achieve is to import a CSV file that will take the file name and save it in the list table, then create an array through the CSV file and import the data into the client table with the list and client ID.

I have the first part, and it is inserted correctly in the list table. How can I now create an array from CSV, which is located in the repository / documents, and then insert it into the client table?

 namespace App\Http\Controllers; use Input; use DB; use Illuminate\Http\Request; use App\Http\Requests\ListsRequest; use App\Lists; use App\Clients; use App\Http\Requests; use App\Http\Controllers\Controller; class ListsController extends Controller { public function index() { // $list_items = Lists::all(); $clients = Clients::all(); return view('lists.show', compact('clients')); } public function store(Requests\ListsRequest $request) { $input = $request->input(); Lists::create($input); if (Input::hasFile('name')) { $file = Input::file('name'); $name = time() . '-' . $file->getClientOriginalName(); $path = storage_path('documents'); $file->move($path, $name); // All works up to here // All I need now is to create an array // from the CSV and insert into the customers database } } } 

I decided to use the answer that I accepted, but I also played with a different answer and made it work as follows.

 public function store(Requests\ListsRequest $request) { $input = $request->input(); $client_id = $request->input('client_id'); if (Input::hasFile('name')) { $file = Input::file('name'); $name = time() . '-' . $file->getClientOriginalName(); $path = storage_path('documents'); Lists::create(['client_id' => $client_id, 'name' => $name]); $reader = Reader::createFromPath($file->getRealPath()); // Create a customer from each row in the CSV file $headers = array(); foreach ($reader as $index => $row) { if ($index === 0) { $headers = $row; } else { $data = array_combine($headers, $row); Customers::create($data); } } $file->move($path, $name); return view('clients'); } } 
+5
source share
2 answers

There are 3 steps to reading a CSV file and importing it into a database in Laravel.

  • Reading CSV File
  • Convert it to an array
  • Finally, create entries in our database.

Before starting, I created a test.csv sample and placed it in my shared folder in the file folder:

 name,email,password user1, email1@email.com ,pasxxxxxxxxxword user2, email2@email.com ,pasxxxxxxxxxword user3, email3@email.com ,pasxxxxxxxxxword 

Step 1 and 2; I created a helper function called csvToArray , now I just put it in my controller (this function is inspired by this link ), it just reads the CSV file and convert it to an array:

 function csvToArray($filename = '', $delimiter = ',') { if (!file_exists($filename) || !is_readable($filename)) return false; $header = null; $data = array(); if (($handle = fopen($filename, 'r')) !== false) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) { if (!$header) $header = $row; else $data[] = array_combine($header, $row); } fclose($handle); } return $data; } 

Step 3; And here is my last step, read the array and paste it into our database:

 public function importCsv() { $file = public_path('file/test.csv'); $customerArr = $this->csvToArray($file); for ($i = 0; $i < count($customerArr); $i ++) { User::firstOrCreate($customerArr[$i]); } return 'Jobi done or what ever'; } 

Note. this solution assumes that you have a model in your Laravel project and the table has a corresponding table.

if you use dd($customerArr) you will get this enter image description here

+10
source

In your store() method, create an entry in your lists table, then navigate to the contents of the CSV file and paste the data into the customers table. You must create a relation between clients and lists for this purpose. You would also be better off using something like the PHP League CSV package to read such files:

 public function store(AddCustomersRequest $request) { // Get uploaded CSV file $file = $request->file('csv'); // Create list name $name = time().'-'.$file->getClientOriginalName(); // Create a list record in the database $list = List::create(['name' => $name]); // Create a CSV reader instance $reader = Reader::createFromFileObject($file->openFile()); // Create a customer from each row in the CSV file foreach ($reader as $index => $row) { $list->customers()->create($row); } // Redirect back to where you need with a success message } 
+1
source

Source: https://habr.com/ru/post/1242358/


All Articles