Importing CSV and Excel data in a Laravel application can be done in several ways. Here is a step-by-step tutorial on how to import CSV and Excel data in a Laravel application:
Table of Contents
Install the maatwebsite package:
Install the maatwebsite package: The first step is to install the maatwebsite package using the composer. Use the following command to install the package:
composer require maatwebsite/excel
Create Controller:
Create a new controller: Next, create a new controller using the following command:
php artisan make:controller ImportController
Import Class:
Add the import class to the controller: In the controller, add the import class to use the import functionality.
use Excel;
Import Function:
Create a new function to import CSV or Excel data: In the controller, create a new function called importData, which will be responsible for importing the CSV or Excel data. The function should look like this:
public function importData(Request $request)
{
$file = $request->file('file');
Excel::import(new UsersImport, $file);
return back();
}
Generate New Import Class:
Create a new import class: Next, create a new import class using the following command:
php artisan make:import UsersImport --model=User
This will create a new import class called UsersImport, which is linked to the User model.
Define the import logic
Define the import logic: In the import class, define the import logic. This is where you can specify how the data should be imported and what should be done with it. Here is an example of how to import data and create new records in the database:
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => Hash::make($row[2]),
]);
}
Create a view: Finally, create a view that will display a form for uploading the CSV or Excel file. The form should include a file input field and a submit button.
Create import Route:
Add a route for the import function: In the routes/web.php file, add a route for the import function.
Route::post('import-data', [ImportController::class,'importData']);
Test the import functionality: Now, test the import functionality by uploading a CSV or Excel file using the form on the view. Make sure that the data is correctly imported and saved to the database.
This is a basic tutorial on how to import CSV and Excel data in a Laravel application. You can customize the import logic and add validation and error handling as needed.