Laravel 10 Import Export Excel & CSV File Example
In this post, we will give you information about Laravel 10 Import Export Excel & CSV File Example. Hear we will give you detail about Laravel 10 Import Export Excel & CSV File Example And how to use it also give you demo for it if it is necessary.
Laravel Excel is designed at being a Laravel-flavoured PhpSpreadsheet. It is a manageable and elegant wrapper around PhpSpreadsheet to simplify exports and imports. PhpSpreadsheet is a php based library that enables you to read and write different spreadsheet file formats, like Excel and LibreOffice Calc. Laravel Excel has the following features:
- Easily export collections to Excel.
- Export queries with automatic chunking for better performance.
- Queue exports for better performance.
- Easily export Blade views to Excel.
- Easily import to collections.
- Read the Excel file in chunks.
- Handle the import inserts in batches.
If you want to create easy import and export, excel file functionality, this laravel maatwebsite/excel tutorial is best for you.
At the end of this tutorial, you will be able to download or import excel & CSV files directly from the database in laravel application.
Requirements
- PHP:
^8.0
- Laravel:
^10.0
- PhpSpreadsheet:
^1.15
- PHP extension
php_zip
enabled - PHP extension
php_xml
enabled - PHP extension
php_gd2
enabled - PHP extension
php_iconv
enabled - PHP extension
php_simplexml
enabled - PHP extension
php_xmlreader
enabled - PHP extension
php_zlib
enabled
Step 1: Install Laravel Project for Laravel 10 Import Export Excel & CSV File Example
First, open Terminal and run the following command to create a fresh laravel project:
composer create-project --prefer-dist laravel/laravel laravel-excel
or, if you have installed the Laravel Installer as a global composer dependency:
laravel new laravel-excel
Step 2: Configure Database Details
After, Installation Go to the project root directory, open .env file, and set database detail as follow:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
Step 3: Install maatwebsite/excel package
You can install Laravel Excel via composer. You’ve to run this command for the installation.
composer require maatwebsite/excel
Register Plugin’s Service in Providers & Aliases
You can have the following code placed inside the config/app.php file.
'providers' => [
MaatwebsiteExcelExcelServiceProvider::class,
],
'aliases' => [
'Excel' => MaatwebsiteExcelFacadesExcel::class,
],
Execute the vendor, publish the command, and publish the config.
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config
This will create a new config file named config/excel.php
.
Step 4: Generate Fake Data and Migrate Table
In the First step, We migrate the user table. After migration run successfully We moved to the second step.
php artisan migrate
In the Second Step, We generate the fake record. Here We use tinker to generate the fake records. You can use a different method as of your requirement.
php artisan tinker
After Opening the tinker, you need to run this command to generate the fake records in our database.
User::factory()->count(100)->create();
Step 5: Create a Routes
In this step, We will add a route to handle requests for import and export files.
use AppHttpControllersUserController;
Route::get('/file-import',[UserController::class,'importView'])->name('import-view');
Route::post('/import',[UserController::class,'import'])->name('import');
Route::get('/export-users',[UserController::class,'exportUsers'])->name('export-users');
Step 6: Create Import Class
Maatwebsite provides a way to build an import class and we have to use it in the controller. So it would be a great way to create a new Import class. So you have to run the following command and change the following code on that file:
php artisan make:import ImportUser --model=User
app/Imports/ImportUser.php
<?php
//Laravel 10 Import Export Excel & CSV File Example
namespace AppImports;
use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;
class ImportUser implements ToModel
{
/**
* @param array $row
*
* @return IlluminateDatabaseEloquentModel|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => bcrypt($row[2]),
]);
}
}
Here you can see map CSV or excel column value to our Eloquent Model. You need to format that CSV or excel column as you map in your import class.
Maatwebsite provides a way to build an export class and we have to use it in the controller. So it would be a great way to create a new export class. So you have to run the following command and change the following code on that file:
php artisan make:export ExportUser --model=User
app/Exports/ExportUser.php
<?php
//Laravel 10 Import Export Excel & CSV File Example
namespace AppExports;
use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
class ExportUser implements FromCollection
{
/**
* @return IlluminateSupportCollection
*/
public function collection()
{
return User::select('name','email')->get();
}
}
Step 8: Create Controller
Next, We have to create a controller to display a form to upload CSV or excel file records. Let’s Create a controller named UserController
using the command given below:
php artisan make:controller UserController
Once the above command is executed, it will create a controller file UserController.php in app/Http/Controllers directory. Open UserController.php file and put this code into that file.
<?php
// Laravel 10 Import Export Excel & CSV File Example
namespace AppHttpControllers;
use IlluminateHttpRequest;
use MaatwebsiteExcelFacadesExcel;
use AppImportsImportUser;
use AppExportsExportUser;
use AppModelsUser;
class UserController extends Controller
{
public function importView(Request $request){
return view('importFile');
}
public function import(Request $request){
Excel::import(new ImportUser, $request->file('file')->store('files'));
return redirect()->back();
}
public function exportUsers(Request $request){
return Excel::download(new ExportUser, 'users.xlsx');
}
}
Step 9: Create Blade / View Files
We have reached the last step. In general, here we need to formulate the view for handling importing and exporting through the front end. Create a resources/views/importFile.blade.php file to set up the view. Place the following code inside the blade view file:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 10 Import Export Excel & CSV File Example - onlinecode</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div >
<h3 >
Laravel 10 Import Export Excel & CSV File Example - <a href="https://onlinecode.org/laravel-import-export-excel-csv-file?ref=repo" target="_blank">onlinecode</a>
</h3>
<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<div >
<div >
<input type="file" name="file" id="customFile">
<label for="customFile">Choose file</label>
</div>
</div>
<button >Import Users</button>
<a href="{{ route('export-users') }}">Export Users</a>
</form>
</div>
</body>
</html>
Run Laravel Application for Laravel 10 Import Export Excel & CSV File Example
Lastly, we have to run the Laravel application, for this, we have to go to the command prompt, and write the following command:
php artisan serve
After executing this command, Open http://localhost:8000/file-import in your browser.
Hope this code and post will helped you for implement Laravel 10 Import Export Excel & CSV File Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs