Supercharged Excel exports and imports
A simple, but elegant Laravel wrapper around PhpSpreadsheet
exports and imports.
Quickstart
·
Documentation
·
Video Course
·
Nova
·
Blog
·
Contributing
·
Support
✨ Features
-
Easily export collections to Excel. Supercharge your Laravel collections and export them directly to an Excel or CSV document. Exporting has never been so easy.
-
Supercharged exports. Export queries with automatic chunking for better performance. You provide us the query, we handle the performance. Exporting even larger datasets? No worries, Laravel Excel has your back. You can queue your exports so all of this happens in the background.
-
Supercharged imports. Import workbooks and worksheets to Eloquent models with chunk reading and batch inserts! Have large files? You can queue every chunk of a file! Your entire import will happen in the background.
-
Export Blade views. Want to have a custom layout in your spreadsheet? Use a HTML table in a Blade view and export that to Excel.
🎓 Learning Laravel Excel
You can find the full documentation of Laravel Excel on the website.
We welcome suggestions for improving our docs. The documentation repository can be found at https://github.com/SpartnerNL/laravel-excel-docs.
Some articles and tutorials can be found on our blog: https://medium.com/maatwebsite/laravel-excel/home
📬 License & Postcardware
Laravel Excel is created with love and care by Spartner (formerly known as Maatwebsite) to give back to the Laravel community. It is completely free (MIT license) to use, however the package is licensed as Postcardware. This means that if it makes it to your production environment, we would very much appreciate receiving a postcard from your hometown.
Spartner
Markt 2
6231 LS Meerssen
The Netherlands.
More about the license can be found at: https://docs.laravel-excel.com/3.1/getting-started/license.html
Created by Spartner (formerly Maatwebsite)
We are a strategic development partner, creating web-based custom built software from Laravel. In need of a digital solution for your challenge? Give us a call.
https://spartner.software
info@spartner.nl
+31 (0) 10 — 7449312
🔧 Supported Versions
Versions will be supported for a limited amount of time.
Version | Laravel Version | Php Version | Support |
---|---|---|---|
2.1 | <=5.6 | <=7.0 | Unsupported since 15-5-2018 |
3.0 | ^5.5 | ^7.0 | Unsupported since 31-12-2018 |
3.1 | >=5.8 | <=10.x | ^7.2 | ^8.0 | New features |
Home » Laravel » Laravel 9 Import Export Excel & CSV File Tutorial
This tutorial helps you understand how to comfortably import export excel or CSV file to Database with Laravel.
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 file directly from the database in laravel application, respectively.
Generically, we will follow all the imperative that are needed to build a general laravel application. We will go from point a to b, something like creating or importing data to xls or CSV.
Laravel 9 Import Export Excel & CSV File to Database Example
Preferably, we will use a maatwebsite/excel composer plugin for exporting and importing data, most importantly, to interact with the database.
I will share the working pattern with you. Ideally, how should you import-export and download the excel & CSV file from the database using the maatwebsite/excel composer plugin.
Follow the given below steps that will take you to the learning dimension.
Table of Contents
- Download Laravel Application
- Compose Database Connection
- Install Excel (maatwebsite) Pacakage
- Generate Fake Records and Migrate
- Construct Route
- Make Import Class
- Construct Export Class
- Create and Prepare Controller
- Write Down Blade View
- Summary
Download Laravel Application
Let’s evoke this tutorial with the imperative step; installing a brand new laravel application offers us a key to opening the many opportunities. We can create the app from the beginning, build multiple features with it.
You can skip this step if you’ve already installed the app. Otherwise, put the command into effect to download the sacred canon.
composer create-project laravel/laravel laravel-excel-csv --prefer-dist
Later on, after the project installation, execute the command to enter the project directory.
cd laravel-excel-csv
Compose Database Connection
Make the consensus between laravel app and MySQL database, append the following code in .env
file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.
UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
Install Excel (maatwebsite) Pacakage
Commonly, to complete our foundational work, we require a third-party package. Ideally, we are talking about the Laravel-Excel plugin by Maatwebsite. It provides the robust mechanism to deal with Excel exports and imports in Laravel. In response, It has got the immense love of artisan’s on GitHub.
Run command to install the package.
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 command, and publish the config.
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
This will formulate a new config file as config/excel.php.
Generate Fake Records, Migrate Table
Often, this step consists of two sub-steps. In the first one, we migrate the User table. Laravel comes with the User model and migration with default values, and we can use it and migrate to the database.
php artisan migrate
Once the migration is completed, then execute the command to generate the fake records.
php artisan tinker
User::factory()->count(50)->create();
exit
Eventually, the above command has created the some data inside the database.
Construct Route
Usually, routing in laravel is the foundational mechanism that interprets the URI endpoint and conjugates it into parameters to shape which module or controller is associated.
Define 3 routes in routes/web.php that handle the import and export for Excel and CSV files.
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersUserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('file-import-export', [UserController::class, 'fileImportExport']);
Route::post('file-import', [UserController::class, 'fileImport'])->name('file-import');
Route::get('file-export', [UserController::class, 'fileExport'])->name('file-export');
Make Import Class
The maatwebsite module offers an imperative method to develop an import class. Obviously, it should be used along with the laravel controller, and i believe you already know this has been the best way to generate a new import class.
Execute the below command:
php artisan make:import UsersImport --model=User
Place the following code inside the app/Imports/UsersImport.php file.
<?php
namespace AppImports;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
class UsersImport implements ToModel
{
/**
* @param array $row
*
* @return IlluminateDatabaseEloquentModel|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => Hash::make($row[2])
]);
}
}
Construct Export Class
The maatwebsite module provides an essential method to construct an export class. Preferably, it needs to get along with the laravel controller, and i know it doesn’t sound vague.
Run the following command in your terminal:
php artisan make:export UsersExport --model=User
Here is the final code that is conjugated in app/Exports/UsersExport.php.
<?php
namespace AppExports;
use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
class UsersExport implements FromCollection
{
/**
* @return IlluminateSupportCollection
*/
public function collection()
{
return User::all();
}
}
Create and Prepare Controller
Now, we have reached an essential step in this tutorial. We will evoke this step by creating a controller. Altogether all the logic goes in here to manage the import and export file such as Excel and CSV.
Invoke the command to generate UserController.
php artisan make:controller UserController
Place the following code in the app/Http/Controllers/UserController.php file.
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use MaatwebsiteExcelFacadesExcel;
use AppImportsUsersImport;
use AppExportsUsersExport;
class UserController extends Controller
{
/**
* @return IlluminateSupportCollection
*/
public function fileImportExport()
{
return view('file-import');
}
/**
* @return IlluminateSupportCollection
*/
public function fileImport(Request $request)
{
Excel::import(new UsersImport, $request->file('file')->store('temp'));
return back();
}
/**
* @return IlluminateSupportCollection
*/
public function fileExport()
{
return Excel::download(new UsersExport, 'users-collection.xlsx');
}
}
Write Down Blade View
Ultimately, we have reached the last step. In general, here we need to formulate the view for handling importing and exporting through the frontend.
Create a resources/views/file-import.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>Import Export Excel & CSV to Database in Laravel 7</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 text-center">
<h2 class="mb-4">
Laravel 7 Import and Export CSV & Excel to Database Example
</h2>
<form action="{{ route('file-import') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group mb-4" style="max-width: 500px; margin: 0 auto;">
<div class="custom-file text-left">
<input type="file" name="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<button class="btn btn-primary">Import data</button>
<a class="btn btn-success" href="{{ route('file-export') }}">Export data</a>
</form>
</div>
</body>
</html>
We have followed every step, respectively, and consecutively, now its time to run the app to test what we build so far.
php artisan serve
Here is the endpoint that you can finally test:
http://localhost:8000/file-import-export
Summary
So this was it, we have completed the tutorial. In this tutorial, we threw light on importing-exporting and downloading the Excel & CSV file from the database with the maatwebsite/excel composer package.
You can also check the documentation of the plugin that we assimilated in this tutorial.
You can download the full code of this tutorial from GitHub.
I hope you must have liked this tutorial, we covered the basic functionality but good for getting started.
Recommended Posts:
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|^8.1
- Laravel:
9.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
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>
Read Also: Laravel 9 CRUD Example Tutorial for Beginners
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
If composer require fails on Laravel 9 because of the simple-cache
dependency, you will have to specify the psr/simple-cache
version as ^2.0
in your composer.json to satisfy the PhpSpreadsheet dependency. You can install both at the same time as:
composer require psr/simple-cache:^2.0 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
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.
Read Also: How to Install MongoDB on Ubuntu 20.04
Step 7: Create Export 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
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 execute, it will create a controller file UserController.php in the app/Http/Controllers directory. Open the UserController.php file and put this code into that file.
<?php
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 frontend. 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 9 Import Export Excel & CSV File - TechvBlogs</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 text-center">
<h2 class="mb-4">
Laravel 9 Import Export Excel & CSV File - <a href="https://techvblogs.com/blog/laravel-9-import-export-excel-csv-file" target="_blank">TechvBlogs</a>
</h2>
<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group mb-4">
<div class="custom-file text-left">
<input type="file" name="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<button class="btn btn-primary">Import Users</button>
<a class="btn btn-success" href="{{ route('export-users') }}">Export Users</a>
</form>
</div>
</body>
</html>
Run Laravel Application
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.
Thank you for reading this blog.
Read Also: How To Install Vue 3 in Laravel 9 From Scratch
If you want to manage your VPS / VM Server without touching the command line go and Checkout this link. ServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a matter of minutes. You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.
If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.
For web applications, importing Excel sheet data into our database and exporting data from the database into an Excel sheet, is an important feature. Because of this feature, we can easily perform batch import/export data by the web application. It is difficult in other Frameworks but easiest in laravel 8. It gives Maatwebsite/excel package to easily import/export data. In this article, we learn about, how data is exported and imported.
Features:
- Effectively send out assortments to Excel.
- Send out questions with programmed piecing for better execution.
- Line sends out for better execution.
- Effectively send out Blade perspectives to Excel.
- Effectively import to accumulations.
- Peruse the Excel record in pieces.
- Handle the import embeds in clumps.
Steps to laravel Import Export excel data: We want to follow a few steps to import and export data easily. There are 9 easy steps to follow.
- Install new laravel project
- Configure Database details and model
- Install maatwebsite/excel package
- Create Routes
- Create import class for import data
- Create an export class for export data
- Create controller
- Create blade / view files
- Run laravel project
1. Install new laravel project: In step first, create a new laravel project named laravel-excel. Use the below command to create a new laravel project.
composer create-project laravel/laravel excel
2. Configure Database details and make a model: In the second step, set up database configuration in the .env file in laravel 8.
PHP
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8258
DB_DATABASE=laravel
DB_USERNAME=localhost
DB_PASSWORD=
Make model: Then make a new model named User model to connect with the user table in the database. In user, the table contains various fields like ID, name, phone, and email.
3. Install maatwebsite/excel Package: Now, using composer we install package name maatwebsite/excel to export and import data by using composer
composer require maatwebsite/excel
After installing the package we want to register the plugin’s service in providers and aliases.
We want to write the following code into the config/app.php file:
PHP
<?php
'providers'
=> [
MaatwebsiteExcelExcelServiceProvider::
class
, ],
'aliases'
=> [
'Excel'
=>
MaatwebsiteExcelFacadesExcel::
class
, ],
?>
To publish the above configuration execute the vendor:publish command:
php artisan vendor:publish –provider=”MaatwebsiteExcelExcelServiceProvider” –tag=config
This command is to create a new config file config/excel.php
4. Create Routes: Then we create routes to handle requests from import and export files.
PHP
<?php
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'
);
?>
5. Create Import class import for import data: The package maatwebsite/excel provides you to build an import class file. Using the following command, we create an import class file.
php artisan make:import ImportUser --model=User
The file will create at the app/Imports/ImportUser.php path:
PHP
<?php
namespace
AppImports;
use
AppModelsUser;
use
MaatwebsiteExcelConcernsToModel;
class
ImportUser
implements
ToModel
{
public
function
model(
array
$row
)
{
return
new
User([
'name'
=>
$row
[0],
'email'
=>
$row
[1],
'password'
=> bcrypt(
$row
[2]),
]);
}
}
6. Create an Export class for export data: The package maatwebsite/excel provides you to build an export class file. Using the following command, we create an export class file.
php artisan make:export ExportUser --model=User
The file will create at the app/Exports/ExportUser.php path:
PHP
<?php
namespace
AppExports;
use
AppModelsUser;
use
MaatwebsiteExcelConcernsFromCollection;
class
ExportUser
implements
FromCollection {
public
function
collection()
{
return
User::select(
'name'
,
'email'
)->get();
}
}
?>
7. Create Controller: To display data from the database, we need to create one controller. Using the below command we create a controller named UserController.
php artisan makes: controller UserController
The above command will create a controller file UserController.php at the path app/Http/controllers directory.
Write the below code into the UserController.php file:
PHP
<?php
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'
);
}
}
?>
8. Create Blade/View file: To handle export and import at frontend of a web application, we need to create a view or blade file. Create a blade file at resources/views/importFile.blade.php:
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
> Import and Export Excel data to database Using Laravel 5.8 </
title
>
<
link
rel
=
"stylesheet"
href
=
</
head
>
<
body
>
<
h6
> Import and Export Excel data to
database Using Laravel 5.8
</
h6
>
<
div
class
=
"container"
>
<
div
class
=
"card bg-light mt-3"
>
<
div
class
=
"card-header"
>
Import and Export Excel data
to database Using Laravel 5.8
</
div
>
<
div
class
=
"card-body"
>
<
form
action
=
"{{ route('import') }}"
method
=
"POST"
enctype
=
"multipart/form-data"
>
@csrf
<
input
type
=
"file"
name
=
"file"
class
=
"form-control"
>
<
br
>
<
button
class
=
"btn btn-success"
>
Import User Data
</
button
>
<
a
class
=
"btn btn-warning"
href
=
"{{ route('export') }}"
>
Export User Data
</
a
>
</
form
>
</
div
>
</
div
>
</
div
>
</
body
>
</
html
>
9. Run laravel project: Run the below command on command prompt and check http://localhost:8000/file-import in the browser:
php artisan serve
Output:
Laravel Import Export
In your admin side, you need to download data in excel format. You also want to import data in database from the excel file. Excel export and import is basic requirement in the admin panel.
Maatwebsite/Laravel-Excel is simple and easy to implement Laravel package. In this article, we will share you how you can export and import data in excel format. We will create Laravel application from the scratch and implement excel export and import.
We will go through step by step. So let’s get started below step by step:
- Create fresh Laravel application
- Create database migration
- Install Maatwebsite/Laravel-Excel Package
- Create routes and controller class.
- Create excel export/import classes file.
- Create blade file
Step: 1. Create Laravel application
In the first step, we will create new Laravel application using bellow command, So open your Terminal or command prompt and run bellow command:
composer create-project laravel/laravel excel
Step 2. Database migration
In your .env file, set the database name and MySQL users data.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=excel
DB_USERNAME=root
DB_PASSWORD=root
Laravel default have migration for users table. So we will use users data for excel export and import. Run the migration command to run create the table in database.
php artisan migrate
Step: 3. Install Maatwebsite/Laravel-Excel Package
In the third step, we will install Maatwebsite/Laravel-Excel package using below command.
composer require maatwebsite/excel
Now open config/app.php
file and register package class in $providers array.
'providers' => [
...
MaatwebsiteExcelExcelServiceProvider::class,
]
In the same file add the class in $aliases array.
'aliases' => [
...
'Excel' => MaatwebsiteExcelFacadesExcel::class,
]
Now publish the package config file. This will add config/excel.php file. You can change the settings for the excel from this file.
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config
Step: 4. Create routes and controller class.
Now we need to create routes of import export file. so open your routes/web.php
file and add below routes.
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersExcelController;
Route::get('excel/view', [ExcelController::class, 'index'])->name('index');
Route::get('excel/export', [ExcelController::class, 'export'])->name('export');
Route::post('excel/import', [ExcelController::class, 'import'])->name('import');
Now create the controller to handle the routes.
php artisan make:controller ExcelController
This will create controller file at app/Http/Controllers/ExcelController.php
. Open the file add the methods as we have defined in route file.
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppExportsUsersExport;
use AppImportsUsersImport;
use MaatwebsiteExcelFacadesExcel;
class ExcelController extends Controller
{
/**
* @return IlluminateSupportCollection
*/
public function index()
{
return view('index');
}
/**
* @return IlluminateSupportCollection
*/
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
/**
* @return IlluminateSupportCollection
*/
public function import()
{
Excel::import(new UsersImport,request()->file('excel'));
return back();
}
}
Step: 5. Create excel export/import classes file.
We have defined controller file. From the controller we will call excel class and make export and import. So we need to create export and import class.
Create import class using below command.
php artisan make:import UsersImport --model=User
Open app/Imports/UsersImport.php
and add the below codes.
<?php
namespace AppImports;
use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;
class UsersImport implements ToModel
{
/**
* @param array $data
*
* @return IlluminateDatabaseEloquentModel|null
*/
public function model(array $data)
{
return new User([
'name' => $data[0],
'email' => $data[1],
'password' => Hash::make($data[2]),
]);
}
}
Same way run command for export
php artisan make:export UsersExport --model=User
<?php
namespace AppExports;
use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
class UsersExport implements FromCollection
{
/**
* @return IlluminateSupportCollection
*/
public function collection()
{
return User::all();
}
}
Step: 6. Create blade file.
In this last step we will create view file where we will export and import excel file.
Create resources/views/index.blade.php file and add the HTML code.
<!DOCTYPE html>
<html>
<head>
<title>Excel Export/Import</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col-12">
<form action="{{ route('import') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label for="excel" class="form-label"></label>
<input type="file" name="excel" class="form-control">
</div>
<button class="btn btn-success">Import User Data</button>
<a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
</form>
</div>
</div>
</div>
</body>
</html>
Now run the artisan command to start Laravel application.
php artisan serve
Open your browser and go to https://localhost:8000/excel/view
You can simply upload the data and import.
Thanks for giving time in reading article. I hope you liked this article and will help you.
Admin・ 6 Oktober 2021
10 min read ・ 2634 views
Laravel Excel Import — In an administrative system, the presence of an excel import feature is needed. This is because to facilitate the work of an admin or worker in inputting reports or data in a system. To create an excel import feature in a system is very easy. There are many available packages that can be used. Especially if the system is made with the laravel framework, we can use the laravel excel package.
In this article, we will discuss how to make the import excel feature in laravel with the laravel excel package. In this experiment, we will start from scratch or start by installing the latest laravel (laravel version 8).
Alright, here are the steps on how to make the import excel feature in laravel 8 with the laravel excel package:
Table of Contents
- Step 1: Install Laravel
- Step 2: Install laravel excel package
- Step 3: Create New Database
- Step 4: Migrate
- Step 5: Create Import Class
- Step 6: Setup Route
- Step 7: Edit welcome.blade.php
- Testing
- Conclusion
Step 1: Install Laravel
composer create-project laravel/laravel importexcel
The first step is to install or create a new laravel project in the folder we want. Install laravel using composer with command as above in terminal. After the process is complete, we will get a new folder or laravel project folder in the directory or folder we want.
Step 2: Install laravel excel package
composer require maatwebsite/excel
Second, we have to install the package that we will use to create the Excel import feature in Laravel. Run the command as above to install it.
Step 3: Create New Database
We need a database to hold the table that contains the imported data. Therefore, please create a new database first in xampp, laragon, or others.
*Don’t forget to match DB_DATABASE in the .env file with the name of the new database that has been created.
Step 4: Migrate
php artisan migrate
We need a table to accommodate the data that will be imported later, therefore we need to migrate the files in the migration folder to the newly created database. Run the php artisan migrate command to migrate the tables.
Step 5: Create Import Class
php artisan make:import UsersImport --model=User
To be able to use the package from laravel excel, we need an import class. For that, please run the command above in the terminal. Running the above command will create a UsersImport.php file that is linked to the User.php model.
Then next we need to edit a bit in the UsersImport.php file. Open the UsersImport.php file which is located in the AppImports folder and according to the code it becomes as below.
<?php
namespace AppImports;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use MaatwebsiteExcelConcernsToModel;
class UsersImport implements ToModel
{
/**
* @param array $row
*
* @return User|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => Hash::make($row[2]),
]);
}
}
In this experiment, we create an Excel import feature in Laravel for user data management. Therefore, if you look at the arrangement of the code above, there is AppModelsUser and the return points to the new user. The data to be imported include name, email and password.
Step 6: Setup Route
In order for the import excel feature to work perfectly, we need a route like the one below.
<?php
use IlluminateSupportFacadesRoute;
use AppImportsUsersImport;
use MaatwebsiteExcelFacadesExcel;
use AppModelsUser;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
$user = User::all();
return view('welcome',['user'=>$user]);
});
Route::post('/', function () {
Excel::import(new UsersImport, request()->file('file'));
return back();
});
If we look at the code above, we will use Laravel’s default homepage route to display user data in a table and add an upload form on the same page.
And since we’re calling import on the route instead of the controller, we need to add code like the one below that’s included in the overall code sample in the web.php file above.
use AppImportsUsersImport;
use MaatwebsiteExcelFacadesExcel;
use AppModelsUser;
Step 7: Edit welcome.blade.php
Because we are using Laravel’s default homepage to display user data and upload form, therefore we need to edit the welcome.blade.php file. Replace all the code in the welcome.blade.php file to be as below.
<!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</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Styles -->
<style>
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm:rounded-lg{border-radius:.5rem}.sm:block{display:block}.sm:items-center{align-items:center}.sm:justify-start{justify-content:flex-start}.sm:justify-between{justify-content:space-between}.sm:h-20{height:5rem}.sm:ml-0{margin-left:0}.sm:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm:pt-0{padding-top:0}.sm:text-left{text-align:left}.sm:text-right{text-align:right}}@media (min-width:768px){.md:border-t-0{border-top-width:0}.md:border-l{border-left-width:1px}.md:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}}
</style>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<style>
body {
font-family: 'Nunito';
}
</style>
</head>
<body class="antialiased">
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 sm:items-center sm:pt-0">
<div class="container">
<div class="row">
<form action="/" method="post" enctype="multipart/form-data">
@csrf
<div class="input-group mb-3">
<input type="file" name="file" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username" aria-describedby="button-addon2">
<button class="btn btn-primary" type="submit" id="button-addon2">Import</button>
</div>
</form>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Password</th>
</tr>
</thead>
<tbody>
@php
$no = 0;
@endphp
@forelse ($user as $user)
<tr>
<th scope="row">{{ ++$no }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->password }}</td>
</tr>
@empty
<td colspan="4" class="table-active text-center">Tidak Ada Data</td>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Testing
After following the steps to create the Laravel Excel import feature above, now comes the testing step. First, prepare the excel file that will be imported later. This excel file contains user data according to what we are currently making, which is to create an excel import feature in Laravel for user data management. The excel format that must be created can be seen as shown below.
After the excel file is ready, now please run the project server with php artisan serve.
Here we do not have user data at all, therefore we can add it with the import feature. Click the form file, find the excel file that has been prepared and then click the import button.
Succeed. We have successfully added user data with the Excel import feature in Laravel using the Laravel Excel package.
Conclusion
In this article we have tried how to make the import excel feature in laravel using the laravel excel package and at the end we have also tested by trying to create an excel file that contains user data including name, email and password then try to upload the excel file that has been created it in the import form. And the results of this experiment we have succeeded in importing excel in the laravel project. So this article has discussed how to easily make the import excel feature in Laravel 8 using the Laravel Excel package, which may only take about 5 minutes during trial practice. If you have criticism, suggestions, input or anything you want to discuss, please write them in the comment form below.
Introduction
We have seen a few Laravel tutorials for beginners and through one of our blog posts, we received a query- Laravel 8 export data excel file with example. So here we are with another Laravel tutorial!
In this step-by-step guideline of Laravel 8 export data as excel file, we will build a demo application in which we will use the maatwebsite/excel package for exporting data. You might be familiar with the package; it provides the best way for exporting the data as a CSV file or Excel file.
We will build a demo application where we will see how to implement Excel export functionality in Laravel using the maatwebsite/excel package.
Before starting the development part, let’s see the below video so that you can have an idea of what are we going to build in this blog.
Create a Model with Migration
Run this command to create a modal
php artisan make:model Student -m
// Student.php
Here we have to store the student data to create a table and define the table’s fields.
Create a Data Table
Go to the database/migration folder, then open the migration file and write the following code.
// 2021_07_16_041455_create_students_table
id(); $table->string('name'); $table->string('email'); $table->string('city'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } }
We will create a table using the above fields.
Now run this command. This command is useful for creating actual tables in the GUI and migrating tables in the database.
php artisan migrate
Install maatwebsite/excel package
To install maatwebsite/excel, run the below-mentioned command
composer require maatwebsite/excel.
With the help of this package, we can export data into an excel file.
Now open config/app.php and add service provider and alias.
'providers' => [ .... MaatwebsiteExcelExcelServiceProvider::class, ], 'aliases' => [ .... 'Excel' => MaatwebsiteExcelFacadesExcel::class, ],
Define the routes
Routes are required for navigating the web pages for defining routes in our demo app, open routes/web.php, and use the following code.
// web.php
Route::resource('student', StudentController::class); Route::get('student_export',[StudentController::class, 'get_student_data'])->name('student.export');
Create an Export Class
In this section, we will create an export class and define the model to which it is connected. The maatwebsite package offers a way for building an export class so that we can further use it in the controller.
Run the below command for the same.
php artisan make:export StudentExport --model=Student
Here StudentExport class will define the data that we want to export in our excel file.
Go to app/Exports/ StudentExport.php and make the following changes in your code
// StudentExport.php
The heading() function will define the heading, which would be displayed in an excel file.
The collection() method will return the data which we have to export. Here in our demo app, we will export all student data using the Student Model.
Create Controller
Before creating the controller we have to make a request.
The command for creating a request.
php artisan make::request StoreStudentRequest
Here are the validation rules applied for entering student data.
public function rules() { return [ 'name' => 'bail|required|string|max:255', 'email' => 'bail|required|string|email|max:255', 'city' => 'bail|required|string|max:255' ]; } }
Run this command to create a resource controller for writing the logic.
php artisan make:controller StudentController –resource
Go to app/Http/Controllers/StudentController.php and write a code.
// StudentController.php
name = $request->name; $student->email = $request->email; $student->city = $request->city; $student->save(); return redirect(route('student.index'))->with('success','Data submited successfully!'); } /** * Display the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param IlluminateHttpRequest $request * @param int $id * @return IlluminateHttpResponse */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return IlluminateHttpResponse */ public function destroy($id) { // } public function get_student_data() { return Excel::download(new StudentExport, 'students.xlsx'); } }
Now we will use the download method of the Laravel excel package within the get_student_data() function. It will accept two parameters: export class and name of the file (you can name it anything you want)
The second parameter is the name of the file in which we want to export the data.
- The create() function is used to create the form.
- The store() method is used to store the data in the database
- The index() method is used to display the data.
Create a View to Add Records and Display Details
Go to the resources/views folder. Create a new folder layout with a file named a main.blade.php
// main.blade.php
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> @yield('title') @yield('content')
Now create another folder within the views folder named student. We have to add the records of the student, and for that, we will need forms. Forms are defined in the view file.
Here main.blade.php is the parent layout file containing all the common header and footer.
In the Student folder, create two files, namely: create.blade.php and index.blade.php.
The create.blade.php file is required to create the form so that students can enter the data. Open create.blade.php and write the following code.
//create.blade.php
@extends('layout.main') @section('title') Registration form @endsection @section('content')@endsectionStudent Registration Form
@csrfName @error('name'){{ $message }}@enderrorEmail @error('email'){{ $message }}@enderrorCity @error('city')Submit{{ $message }}@enderror
In the index.blade.php file, we have displayed the Student data in the table format, and we can easily download the data and export it as an excel file by clicking the Export button.
// index.blade.php
@extends('layout.main') @section('title') Student Data @endsection @section('content')@if ($message = session('success'))@endsection{{ $message }}@endifStudent Data
Export Data Add Data
@foreach ($students as $student) ID Name City @endforeach {{ $student->id }} {{ $student->name }} {{ $student->email }} {{ $student->city }} {{ $students->links() }}
Develop. Maintain. Optimize. Deploy – with Bacancy!
Are you looking for proficient developers to build highly-optimized applications? Get in touch with us to hire Laravel developer. Contact the best, to get the best! Period!
Run the Demo Application
The last section of the tutorial- laravel 8 export data as excel file is to run the app. Now it’s time to run our demo. Run the below command.
php artisan serve
After running the server successfully you can see the app working on
http://localhost:8000/student/create
GitHub Repository
The entire source code is available here: laravel-excel-export-example. Feel free to clone the repo and play around with the code.
Conclusion
So, I hope the tutorial of laravel 8 export data as excel file was helpful to you. Are you a laravel enthusiast and find it difficult for basic tutorials? If yes, then the Laravel tutorials page is for you! Feel free to visit and explore more such laravel tutorials.
Bacancy has dedicated, skilled, and experienced laravel developers with problem-solving skills. If you are looking for laravel developers who can help you with your requirements and project then without wasting your time contact Bacancy and hire laravel developer.