In today's data-driven world, as a Laravel developer, the need to import and export data in different file formats is a common requirement for web applications. With the release of Laravel 10, I now have even more capabilities at my disposal when it comes to handling CSV and Excel files.
These file formats are widely used for data exchange, making it crucial for me to understand how to handle them effectively within my Laravel applications.
In this article, I will explore the process of importing and exporting CSV and Excel files using Laravel 10. I will walk through the necessary steps and demonstrate how Laravel's features and supporting packages can streamline these tasks.
By the end of this article, I will have a solid understanding of how to handle CSV and Excel files within my Laravel applications, empowering me to seamlessly import and export data with confidence.
In particular, I will be leveraging the popular maatwebsite/excel plugin to facilitate the seamless importing and exporting of CSV and Excel files.
In this article, I will guide you through the process of utilizing Laravel 10 in conjunction with the maatwebsite/excel
plugin to handle CSV and Excel files effectively.
We will explore the necessary steps and demonstrate how this combination of Laravel and the maatwebsite/excel
plugin can simplify the import and export processes.
So, whether I need to import large datasets from external sources or export data for reporting or analysis, the capabilities of Laravel 10 will enable me to accomplish these tasks efficiently and effortlessly.
Join me as I dive into the power of Laravel 10 for importing and exporting CSV and Excel files.
Install Laravel 10 by using Composer:
composer create-project --prefer-dist laravel/laravel laravel_10_import_export_csv_excel
In this step, we will configure the database configuration.
- Open the
.env
file in the root directory of your Laravel project. - Set the
DB_CONNECTION
,DB_HOST
,DB_PORT
,DB_DATABASE
,DB_USERNAME
, andDB_PASSWORD
variables according to your database configuration.
For example, if you're using MySQL, the configuration might look like this.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=import_export_csv_excel
DB_USERNAME=root
DB_PASSWORD=root
Install the maatwebsite/excel
plugin using Composer.
composer require maatwebsite/excel
The Maatwebsite\Excel\ExcelServiceProvider
is auto-discovered and registered by default.
If you want to register it yourself, add the ServiceProvider in config/app.php
:
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
]
The Excel
facade is also auto-discovered.
If you want to add it manually, add the Facade in config/app.php
:
'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
To publish the config, run the vendor publish command:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Use the Tinker console to add dummy records to the database. For example, to add 100 dummy user records, run the following command.
php artisan tinker
factory(App\User::class, 100)->create();
Note: Replace App\User
with the appropriate model class representing your users. Adjust the number 100
as per your requirement.
Open the routes/web.php
file in your Laravel project.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImportExportController;
/*
|--------------------------------------------------------------------------
| 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::controller(ImportExportController::class)->group(function(){
Route::get('import_export', 'importExport');
Route::post('import', 'import')->name('import');
Route::get('export', 'export')->name('export');
});
Now, we will create the ImportExportController using the following command.
php artisan make:controller ImportExportController
App/Http/Controllers/ImportExportController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\ExportUsers;
use App\Imports\ImportUsers;
use Maatwebsite\Excel\Facades\Excel;
class ImportExportController extends Controller
{
public function importExport()
{
return view('import');
}
public function export()
{
return Excel::download(new ExportUsers, 'users.xlsx');
}
public function import()
{
Excel::import(new ImportUsers, request()->file('file'));
return back();
}
}
Run the following command to generate an import class
php artisan make:import ImportUsers --model=User
After running this command you will find the ImportUsers.php file.
app\Imports\ImportUsers.php
<?php
namespace App\Imports;
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
class ImportUsers implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
]);
}
}
Now, we will create the export class using the below command.
php artisan make:export ExportUsers --model=User
After running this command you will find the ExportUsers.php file.
app\Export\ExportUsers.php
<?php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExportUsers implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::all();
}
}
Start building the content of the import.blade.php
file. This file is a Blade template that will define the HTML structure and any necessary form elements for the import functionality.
resources/views/import.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title> Laravel 10 Import and Export CSV and Excel Files - Vidvatek </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Laravel 10 Import and Export CSV and Excel Files - Vidvatek</h3>
<form action="{{ route('import') }}" method="POST" name="importform"
enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="file">File:</label>
<input id="file" type="file" name="file" class="form-control">
</div>
<div class="form-group">
<a class="btn btn-info" href="{{ route('export') }}">Export File</a>
</div>
<button class="btn btn-success">Import File</button>
</form>
</div>
</body>
</html>
Now, run the below command in the terminal.
php artisan serve
You might also like:
- Read Also: Convert HTML to PDF in Python: Step-by-Step Guide
- Read Also: Importing Excel File into Database Using Python
- Read Also: AJAX CRUD Operations In Laravel 10: Step-by-Step Guide
- Read Also: Building Complete CRUD Application in Laravel 10