How to Import Excel Data into Database in Laravel
Excel sheets are widely used for managing large datasets. However, in web applications, adding these records to the database manually can be time-consuming. In Laravel, you can import Excel data directly into your MySQL database with ease using the Laravel Excel (Maatwebsite) package.
Why Use Excel Import in Laravel?
- Bulk upload of users, products, or employee data
- Faster migration of old records into your system
- Reduces human error in manual entry
- Helps in financial, HR, and inventory management
Step-by-Step Guide to Import Excel Data in Laravel
1. Install Laravel Excel Package
composer require maatwebsite/excel
2. Create an Import Class
php artisan make:import UsersImport --model=User
Now open app/Imports/UsersImport.php and map your Excel columns to database fields:
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'phone' => $row[2],
]);
}
3. Create Controller for Import
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
public function import(Request $request)
{
Excel::import(new UsersImport, $request->file('file'));
return back()->with('success', 'Excel Data Imported Successfully!');
}
4. Upload Form in Blade File
<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" required>
<button type="submit">Import</button>
</form>
Best Practices
- Validate uploaded file type (.xls, .xlsx, .csv)
- Use database transactions to ensure data integrity
- Log failed rows for debugging
- Always test with small datasets before bulk uploads
Conclusion
By using the Laravel Excel package, you can efficiently import Excel data into your database. This feature is especially useful for applications like ERP, HR, finance, and inventory management systems. With just a few commands and proper validation, you can save significant time and improve efficiency.