Laravel 13 - How to Import & Export Excel Files Using FastExcel.
Laravel 13 - How to Import & Export Excel Files Using FastExcel.
In this tutorial, we will learn how to import and export Excel files in Laravel 13 using FastExcel, set up the required routes and controller, and manage user data with a simple Excel workflow.
Quick Overview
This guide walks you through setting up Excel import and export functionality in a Laravel 13 application using the FastExcel package. It starts by creating a fresh Laravel project and enabling the required PHP ZIP extension, followed by installing FastExcel and creating a dedicated controller for handling user data. You’ll then learn how to configure the application routes and build a user management interface that allows users to import records from an Excel file and export existing users to Excel. Finally, the tutorial shows you how to create test users and verify both import and export functionality. By following these steps, you can add a simple and practical Excel workflow to your Laravel application for managing user data.
Step # 1 : Initialize the Laravel 13 Excel Project.
We’ll begin by setting up a clean Laravel 13 project called excel. Laravel uses Composer to manage its PHP packages, so make sure Composer is already installed before moving ahead. For a smoother setup, you can also use the Laravel Installer. If it’s not installed globally on your machine, install it with.
composer global require laravel/installer
Once the Installer is available, create the new application by running.
laravel new excel
During the installation, Laravel will prompt you to configure the project. Use the following options to proceed.
- Starter Kit: Select No because this project doesn't require any starter kit or pre-built authentication scaffolding.
- Frontend Stack: Choose Blade as the frontend stack. This will keep the application simple and allow us to work with Laravel's built-in Blade templating engine.
- Boost Features: Press Enter to continue with no Boost features enabled. We don't need any of the additional Boost functionality for this project.
- Boost Integrations: Press Enter again to skip the Boost integrations, as they aren't needed for the application's setup.
- AI Agents: Select Amp when Laravel asks you to choose an AI agent. This will configure Amp for the project during the initial setup.
After completing these selections, Laravel will finish creating the excel application with a clean Laravel 13 setup. The project will use Blade on the frontend, while Boost features and integrations will remain disabled and Amp will be configured as the selected AI agent.
Step # 2: Navigate to the Excel Project.
After Laravel finishes creating the application, the next step is to move into the excel project directory. Open your preferred terminal, such as PowerShell, Command Prompt, Git Bash, or the integrated terminal in VS Code, and run.
cd excel
This changes your current working directory to the Laravel project. From here, you can run Artisan commands and continue with the remaining application configuration.
Step # 3 : Enable the ZIP Extension.
Before we install FastExcel, we need to make sure that PHP's ZIP extension is enabled. FastExcel relies on this extension, so it should be enabled before moving on to the package installation. First, locate your php.ini file and look for the following line.
;extension=zip
The semicolon at the beginning means that the extension is currently disabled. Remove it so the line becomes.
extension=zip
Save the changes and restart Apache or your PHP service so the updated configuration takes effect.
If you're using XAMPP, WAMP, or Laragon, you'll usually find php.ini inside the PHP directory. In XAMPP, for example, it's located at: C:\xampp\php\php.ini. On macOS or Linux, run php --ini to find the active configuration file. Open it, enable extension=zip, save the changes, and restart PHP or your web server.
Step # 4 : Install FastExcel Package.
Now, let's add FastExcel to the Laravel application. The Rap2hpoutre/FastExcel package makes it easy to work with Excel and CSV files, allowing us to import and export data without adding unnecessary complexity. Run the following Composer command to install the package.
composer require rap2hpoutre/fast-excel
Once the installation is complete, FastExcel will be available in your Laravel application, giving you a simple and efficient way to work with Excel and CSV files.
Step # 5 : Create a User Excel Controller.
Now that FastExcel is installed, the next step is to create a dedicated controller for handling the Excel operations related to users. Create the controller using the following Artisan command.
php artisan make:controller UserExcelController
Once the controller has been created, open UserExcelController.php, which is located at app/Http/Controllers/UserExcelController.php, and replace its contents 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!');
}
}
The UserExcelController brings the main Excel operations for users together in one place. The index() method loads all users for the welcome page, export() prepares the user ID, name, and email details and downloads them as an Excel file, while import() validates the uploaded file, reads the user data with FastExcel, creates the corresponding records in the database, and assigns a default password to each imported user.
Step # 6: Update Routes.
Next, we’ll update the default application route and add routes for importing and exporting users. Open routes/web.php and update it with the following routes.
use App\Http\Controllers\UserExcelController;
// Display all users on the welcome page
Route::get('/', [UserExcelController::class, 'index'])->name('users.index');
// Export all users to an Excel file
Route::get('/export-users', [UserExcelController::class, 'export'])->name('users.export');
// Import users from an uploaded Excel file
Route::post('/import-users', [UserExcelController::class, 'import'])->name('users.import');
The UserExcelController is now connected to the application's routes. The / route displays the users, /export-users handles the Excel export, and /import-users handles Excel file imports and adds the user records to the database.
Step # 7 : Customize the Welcome Page View.
Now let’s update welcome.blade.php to bring everything together in one simple interface. The page lists the available users in a table and provides separate actions for exporting the current data and uploading an Excel file for import.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shotcut | Laravel 13 Fast Excel Tutorial: Import & Export Users</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-950 min-h-screen text-gray-200">
<div class="max-w-6xl mx-auto px-6 py-12">
<!-- Header -->
<div class="mb-8">
<h1 class="text-3xl font-bold text-white">
Code Shotcut - User Management
</h1>
<p class="mt-2 text-gray-400">
Manage your users and import or export data using Excel.
</p>
</div>
<!-- Success Message -->
@if(session('success'))
<div class="mb-6 rounded-lg border border-green-800 bg-green-900/30 px-5 py-3 text-green-400">
<p class="text-sm">
{{ session('success') }}
</p>
</div>
@endif
<!-- Validation Errors -->
@if($errors->any())
<div class="mb-6 rounded-lg border border-red-800 bg-red-900/30 px-5 py-3 text-red-400">
<p class="text-sm">
{{ implode(' ', $errors->all()) }}
</p>
</div>
@endif
<!-- Main Card -->
<div class="bg-gray-900 border border-gray-800 rounded-2xl shadow-xl overflow-hidden">
<!-- Card Header -->
<div class="px-6 py-5 border-b border-gray-800 flex items-center justify-between">
<div>
<h2 class="text-xl font-semibold text-white">
Users
</h2>
<p class="text-sm text-gray-400 mt-1">
List of all registered users
</p>
</div>
<a href="{{ route('users.export') }}"
class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition">
Export Users
</a>
</div>
<!-- Users Table -->
<div class="overflow-x-auto">
<table class="w-full text-center">
<thead class="bg-gray-800">
<tr>
<th class="w-24 px-6 py-4 text-sm font-semibold text-gray-300">
ID
</th>
<th class="w-1/3 px-6 py-4 text-sm font-semibold text-gray-300">
Name
</th>
<th class="px-6 py-4 text-sm font-semibold text-gray-300">
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-800">
@forelse($users as $user)
<tr class="hover:bg-gray-800/60 transition">
<td class="w-24 px-6 py-4 text-sm text-gray-400">
{{ $user->id }}
</td>
<td class="w-1/3 px-6 py-4 text-sm font-medium text-white">
{{ $user->name }}
</td>
<td class="px-6 py-4 text-sm text-gray-400">
{{ $user->email }}
</td>
</tr>
@empty
<tr>
<td colspan="3" class="px-6 py-8 text-sm text-gray-500">
No users found.
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<!-- Import Section -->
<div class="px-6 py-5 border-t border-gray-800 bg-gray-900">
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h3 class="text-sm font-semibold text-white">
Import Users
</h3>
<p class="text-sm text-gray-400 mt-1">
Upload an Excel file to import users.
</p>
</div>
<form action="{{ route('users.import') }}"
method="POST"
enctype="multipart/form-data"
class="flex flex-col sm:flex-row gap-3">
@csrf
<input
type="file"
name="file"
required
class="block w-full sm:w-auto text-sm text-gray-400
file:mr-4 file:py-2 file:px-4
file:rounded-lg file:border-0
file:bg-gray-700 file:text-gray-200
hover:file:bg-gray-600
border border-gray-700 rounded-lg bg-gray-800">
<button
type="submit"
class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
Import Excel
</button>
</form>
</div>
</div>
</div>
<div class="mt-8 text-center">
<p class="text-sm text-gray-400">
For more Laravel tutorials, practical examples, and web development guides,
visit
<a href="https://codeshotcut.com/"
target="_blank"
rel="noopener noreferrer"
class="text-white font-medium hover:text-blue-400 transition">
Code Shotcut
</a>
or watch our tutorials and
<a href="https://www.youtube.com/@Codeshotcut"
target="_blank"
rel="noopener noreferrer"
class="text-white font-medium hover:text-red-400 transition">
subscribe to our YouTube channel
</a>.
</p>
</div>
</div>
</body>
</html>
The interface is styled with Tailwind CSS and uses Blade to display the users and handle the import/export actions. The export option generates an Excel file from the existing users, while the import form accepts an Excel file and passes it to Laravel for processing. Success and validation messages are also displayed to provide feedback after an import attempt.
Step # 8: Create Test Users with Laravel Factories.
Before testing the Excel import and export features, we need some sample users in the database. Laravel factories make it easy to generate multiple test records with realistic data. Open your preferred terminal, such as Command Prompt, PowerShell, Git Bash, or the VS Code integrated terminal, and run the following command.
php artisan tinker --execute="\App\Models\User::factory()->count(5)->create();"
This will add five fake users to your database, including randomly generated names, email addresses, and passwords. These records will provide the sample data needed to test the Excel import and export functionality.
Step # 9 : Verify Excel Import and Export Functianlity.
Now that everything is set up, let’s test the Excel import and export functionality. Start the Laravel development server by running.
php artisan serve
Once the server is running, open your browser and visit http://127.0.0.1:8000. You should see the list of users on the welcome page.
Export Users
To test the export functionality, click the Export button on the page. Laravel will generate and download a file named users.xlsx containing the ID, Name, and Email of the users stored in your database. Open the downloaded file in Excel to verify that the user data has been exported correctly.
Import Users
For testing the import feature, use the users.xlsx file you just downloaded and update the user details, such as the Name and Email. Make sure each email address remains unique. After saving your changes, click the Import button to upload the file and import the updated user data. You can also use another .xlsx file, as long as it follows the same column structure expected by the controller.
Conclusion
By following this guide, you’ve successfully added Excel import and export functionality to your Laravel 13 application using the FastExcel package. You can now export existing user records to an Excel file and import user data back into the application, making it easier to manage and transfer data. The same approach can also be extended to other models and datasets whenever you need simple Excel or CSV import and export functionality in your Laravel projects.
For more details, refer to the official FastExcel package documentation: https://github.com/rap2hpoutre/fast-excel.
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