Laravel 12 – How to Import & Export Excel Data Using FastExcel.
Laravel 12 – How to Import & Export Excel Data Using FastExcel.
In this tutorial, we will learn how to import and export Excel data in Laravel 12 using FastExcel. You’ll set up the package, create routes and a controller, and manage user records efficiently using Excel or CSV files.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide walks you through integrating Excel import and export functionality into your Laravel 12 application using the FastExcel package. You’ll start by setting up a fresh Laravel project, enabling the ZIP extension, and installing the rap2hpoutre/fast-excel package. A dedicated controller is created to manage exporting users to Excel and importing new users from uploaded files. The routes and welcome view are updated to provide a user-friendly interface where users can be listed, exported, or imported through a simple upload form. Finally, you generate sample users for testing and verify the process by exporting existing users and importing updated data back into the system, all while keeping the workflow fast, clean, and efficient.
Step # 1 : Set Up a New Laravel 12 Application.
Let’s begin by creating a brand-new Laravel 12 project. If you already have the Laravel Installer installed globally, you can create a new project easily by running.
laravel new fast-excel
If not, you can use Composer instead.
composer create-project laravel/laravel fast-excel
When using Composer, you won’t see the interactive setup prompts. Those prompts appear only when using the Laravel Installer. When using the Laravel Installer, you’ll be guided through a few setup prompts.
- When asked about installing a starter kit, select None.
- Next, choose Pest if prompted for a testing framework.
- Select MySQL as your database.
- Confirm with Yes when asked to run the default migrations to create the initial tables.
- Finally, either type Yes if prompted, or run npm install followed by npm run build to install and compile the frontend assets.
You’ll now have a fresh Laravel 12 project named fast-excel, ready for development.
Step # 2 : Move Into Your Laravel Project Folder.
Next, open your terminal (Command Prompt, Git Bash, or Terminal) and switch into your project directory.
cd c:xampp/htdocs/fast-excel
Ensure you’re inside the project root before running any Laravel Artisan or npm commands to avoid path related issues.
Step # 3 : Enable the ZIP Extension.
The FastExcel package requires the PHP ZIP extension. Open your php.ini file and uncomment the line.
;extension=zip
Change it to.
extension=zip
Then save the file and restart Apache or PHP to apply changes. For XAMPP/WAMP/Laragon, the php.ini file is inside the php folder (e.g., C:\xampp\php\php.ini). For macOS/Linux, you can find it by running php --ini, then edit and uncomment extension=zip, and restart your web server or PHP service.
Step # 4 : Install Install FastExcel Package.
We’ll use the Rap2hpoutre/FastExcel package to efficiently handle Excel and CSV file imports and exports in Laravel. Run the following command to install it.
composer require rap2hpoutre/fast-excel
This package provides a fast and simple way to read and write Excel or CSV files using Laravel Collections, making data import and export tasks much easier and more performant.
Step # 5 : Create a User Excel Controller.
Create a UserExcelController using the following command.
php artisan make:controller UserExcelController
Next, Update the UserExcelController with the following code.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Rap2hpoutre\FastExcel\FastExcel;
use Illuminate\Support\Facades\Hash;
class UserExcelController extends Controller
{
// Display the welcome page with all users
public function index()
{
$users = User::all();
return view('welcome', compact('users'));
}
// Export users to Excel, selecting relevant columns and preparing a downloadable file
public function export()
{
$users = User::select('Id','Name','Email')->get();
return (new FastExcel($users))->download('users.xlsx');
}
// Validate uploaded file, import users from Excel, create new users in the database, and set a default password
public function import(Request $request)
{
$request->validate([
'file' => ['required', 'file', 'mimes:xlsx,csv,ods']
]);
(new FastExcel)->import($request->file('file'), function ($row) {
return User::create([
'name' => $row['Name'],
'email' => $row['Email'],
'password' => Hash::make('password123'), // default password
]);
});
// Redirect back with success message
return back()->with('success', 'Users imported successfully!');
}
}
This controller handles all user management for Excel operations. It displays all users on the welcome page, exports selected user data to an Excel file, and imports users from an uploaded Excel file while setting a default password for each new user.
Step # 6: Update Routes
We need to set up routes for viewing users, importing Excel files, and exporting users. Update the web.php file like below.
use App\Http\Controllers\UserExcelController;
// Show all users on the welcome page
Route::get('/', [UserExcelController::class, 'index'])->name('users.index');
// Export all users to Excel
Route::get('/export-users', [UserExcelController::class, 'export'])->name('users.export');
// Import users from Excel
Route::post('/import-users', [UserExcelController::class, 'import'])->name('users.import');
With these routes, the application can now display users, import Excel files, and export users.
Step # 7 : Update the Welcome Page View.
We need to update the welcome.blade.php file to display all users and include a simple interface for importing and exporting users using Excel.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shortcut - Users Fast Excel Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 min-h-screen flex flex-col items-center py-10 text-gray-200">
<div class="bg-gray-800 shadow-lg rounded-xl p-8 w-full max-w-5xl">
<!-- Page Heading -->
<h2 class="text-3xl font-semibold mb-6 text-center text-white">Users Fast Excel Example | Code Shortcut</h2>
<!-- Users Table -->
<div class="overflow-x-auto mb-6">
<table class="w-full border border-gray-700 rounded-lg">
<thead class="bg-gray-700 text-left text-gray-200">
<tr>
<th class="py-2 px-4 border-b border-gray-600">ID</th>
<th class="py-2 px-4 border-b border-gray-600">Name</th>
<th class="py-2 px-4 border-b border-gray-600">Email</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr class="text-left hover:bg-gray-700 transition">
<td class="py-2 px-4 border-b border-gray-600">{{ $user->id }}</td>
<td class="py-2 px-4 border-b border-gray-600">{{ $user->name }}</td>
<td class="py-2 px-4 border-b border-gray-600">{{ $user->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Import / Export Buttons -->
<div class="flex justify-between">
<!-- Import Excel -->
<form action="{{ route('users.import') }}" method="POST" enctype="multipart/form-data" class="flex space-x-2">
@csrf
<input type="file" name="file" required
class="border border-gray-600 rounded-lg p-2 bg-gray-700 text-gray-200 focus:ring-2 focus:ring-blue-500">
<button type="submit"
class="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition">
Import Excel
</button>
</form>
<!-- Export Users -->
<a href="{{ route('users.export') }}">
<button class="bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 transition">
Export Users
</button>
</a>
</div>
</div>
</body>
</html>
Tailwind CSS is used to style the layout, keeping it simple, responsive, and professional, with a dark-themed interface for better readability. This view displays all users in a clean table and provides options to import and export users via Excel. Success messages are shown when users are imported successfully, and validation errors are displayed if the uploaded file is invalid.
Step # 8: Generate Test Users with Factories.
Before testing the import and export functionality, we need some fake users in the database. Laravel factories make it easy to create multiple users quickly for testing purposes. Run the following command in your Git Bash terminal.
php artisan tinker --execute="\App\Models\User::factory()->count(5)->create();"
This will generate 5 fake users with random names, emails, and passwords in your database. Now your database has sample data ready to test importing and exporting Excel files without launching the interactive Tinker shell.
Step # 9 : Testing the Import & Export Functianlity.
Start the Laravel development server by running.
php artisan serve
Once it’s running, open your browser and navigate to http://127.0.0.1:8000, where you should see a list of users.
Export :
To export user details, click on the Export button. This will download a file named users.xlsx containing user information such as ID, Name, and Email. You can use this file to review, share, or make updates to the user data offline.
Import :
For this example, lets's take the users.xlsx file you just downloaded and update the details, such as Name and especially Email, which must remain unique. Once your changes are saved, click the Import button to upload the file and update the users in the system. You can also use any other .xlsx file, but make sure it follows the same format defined in the controller to avoid errors.
Conclusion
By following this guide, you’ve successfully added fast and efficient Excel import and export functionality to your Laravel 12 application. With the Rap2hpoutre/FastExcel package handling data processing, your app can now generate Excel files with user records and seamlessly import new users from uploaded spreadsheets. This feature not only saves time but also improves data management and workflow efficiency for admin users. Feel free to expand this setup further such as adding validation, custom columns, or bulk data updates to match your application needs.
For more details, you can explore the FastExcel package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments