CSV Files into SQL with Laravel

CSV Files into SQL with Laravel

We can convert CSV file into a SQL data without using any third-party packages.

Sometimes we want to import CSV files into Mysql data by using the form submitted in our Laravel project. For this, we are not using any third-party packages.

Here is a sample code that we are going to explain.

image.png

1. The fopen() function opens the file specified by filename and associates a stream with it an 'r' read the file: image.png

2. And then fgetcsv() function can parse a line from an open file and check for CSV fields:

image.png

3. The fclose() function closes an open file pointer. The function returns TRUE on success and FALSE on failure:

image.png

4. Now we can insert data one by one by using a foreach loop.

image.png

5. The upsert method in Laravel will let you insert multiple rows that do not exist and update the rows that already exist with the new values.

image.png