Validate data in csv file with laravel excel

Tram Ho

Preface

I’m sure many of you when working on projects that have been asked to import excel or csv data into a database. Then we will often think of the processing functions that php provides such as fopen to read files, fgetcsv to read csv files … However today I will introduce you to a package that supports us reading, Export excel or csv file very easily and quickly. And that is maatwebsite / excel. But today I’m not going to do normal file import, I’m focusing mostly on validating data in import file. Let’s get started!

Initialize project

First, create a new project laravel

Create route

After web.php the project, go to the web.php file and add the following:

For quick and convenient, I always use the closure function on the route, no need to take time to create controller =)).

Create blade view

Sure, we need an interface to perform the import function. I use the welcome.blade.php file to add the import form:

Now, all you need to do is add a database and we can start validating data from the csv file.

Create the form request

Of course, to validate data records inside the csv file, we first need to validate the file uploaded to the server first, right? Please create a form request as follows:

Laravel will create the ImportCsvFileRequest.php file for us with the following content:

Install Laravel excel

Ok, now we go to the main part of today’s article. Please go to the laravel excel homepage to find out more details. Of course, to use it, we have to install it into the project.

Since we perform the import file function, let’s create the import file:

What do we create these 2 import files? Why create 2 import files? In fact, the name of the file speaks for its purpose. But the details of how you guys wait and see later. Content of UsersImport.php file:

file ValidateCsvFile.php

And finally the route closure () function inside our final web.php file will look like this:

The purpose of the ValidateCsvFile.php file is that we will validate the entire row included in the file, and with the $ errors variable we can show and determine which row is being validated and from which we can fix. file a convenient way.
And with the UsersImport file, when importing each row one by one, we validate again to ensure it cannot pass rows with an invalid value.

Result

And here is the final result we achieved: So we have successfully imported a csv file into the database with extremely easy validate.

Conclude

I have just finished a fairly simple demo of data validation when we import it from the csv file. Hope to help you solve some problems when doing tasks related to importing files. If you have any questions, please comment below. Would like to thank!

Share the news now

Source : Viblo