Payroll Management Software
In the modern business landscape, companies—regardless of size—are striving to optimize operations, enhance employee satisfaction, and ensure compliance with labor laws. One area that sign
Read MoreSign Up Now and Get FREE CTO-level Consultation.
CSV (Comma-Separated Values) files are one of the most popular formats for storing and transferring data between applications. Whether you're importing customer information, employee records, products, inventory, or student details, CSV files provide a quick and efficient way to move large amounts of data into a database.
Laravel, one of the most popular PHP frameworks, makes importing CSV files simple and secure. With its powerful validation system, Eloquent ORM, and built-in file handling capabilities, developers can create a reliable CSV import feature with minimal effort.
In this tutorial, you'll learn how to upload a CSV file and import its data into a MySQL database using Laravel. This guide is beginner-friendly and follows Laravel best practices, making it suitable for both new and experienced developers.
Many businesses work with Excel or CSV files every day. Instead of entering records manually, importing CSV files saves time and reduces errors.
Some common use cases include:
Importing customer information
Uploading employee records
Managing product catalogs
Student admission data
Vendor information
Sales reports
Inventory management
Contact lists
Laravel provides an excellent foundation for building these import systems because it offers secure file uploads, validation, database abstraction, and clean code architecture.
Using Laravel for CSV imports offers several advantages:
Instead of manually adding hundreds or thousands of records, users can upload a single CSV file to import all the data within seconds.
CSV import minimizes human errors that typically occur during manual data entry.
Businesses can update large datasets quickly, allowing employees to focus on more important tasks.
Laravel allows you to validate uploaded files and imported data before saving it into the database.
Laravel protects your application through request validation and secure file upload mechanisms.
Before starting the project, ensure your system has the following installed:
PHP 8.x or later
Composer
Laravel 10 or Laravel 11
MySQL Database
Apache or Nginx
Visual Studio Code (or any code editor)
You should also have basic knowledge of:
PHP
Laravel
MySQL
HTML Forms
First, create a fresh Laravel application using Composer.
composer create-project laravel/laravel csv-import
Navigate to the project directory:
cd csv-import
Start the development server:
php artisan serve
Visit:
http://127.0.0.1:8000
Your Laravel application is now ready.
Open the .env file and update your database credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=csv_import
DB_USERNAME=root
DB_PASSWORD=
After updating the database configuration, clear the configuration cache.
php artisan config:clear
Laravel will now connect to your MySQL database.
Generate a migration for storing users (or any data you want to import).
php artisan make:migration create_users_table
Update the migration file.
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone');
$table->timestamps();
});
Run the migration.
php artisan migrate
The table will now be created in your database.
Generate the model.
php artisan make:model User
Open the User model and define the fillable fields.
protected $fillable = [
'name',
'email',
'phone'
];
This allows Laravel to perform mass assignment safely while importing records.
Generate a controller.
php artisan make:controller CSVImportController
Inside the controller, create methods for displaying the upload page and importing CSV data.
public function index()
{
return view('import');
}
Another method will be used later to process the uploaded CSV file.
Keeping upload logic inside a dedicated controller makes your application organized and easier to maintain.
Open the routes/web.php file and add the following routes.
use App\Http\Controllers\CSVImportController;
Route::get('/import',[CSVImportController::class,'index']);
Route::post('/import',
[CSVImportController::class,'store']);
The GET route displays the upload form, while the POST route processes the uploaded CSV file.
Inside the resources/views folder, create a file named:
import.blade.php
Add the following HTML form.
<form action="/import"
method="POST"
enctype="multipart/form-data">
@csrf
<input type="file" name="csv_file">
<button type="submit">
Upload CSV
</button>
</form>
The multipart/form-data attribute is required because the form uploads a file.
Laravel also requires the @csrf directive to protect against cross-site request forgery (CSRF) attacks.
Before importing data into the database, always validate the uploaded file. Validation prevents users from uploading unsupported file types and helps maintain data integrity.
Inside the store() method of your controller, add validation:
$request->validate([
'csv_file' => 'required|mimes:csv,txt|max:2048'
]);
This validation ensures that:
A file is selected before submission.
Only .csv and .txt file formats are accepted.
The uploaded file size does not exceed the specified limit.
If validation fails, Laravel automatically redirects the user back to the upload page and displays the validation errors.
Validating user uploads is an important security practice because it protects your application from invalid or potentially harmful files.
In Part 1, we created the Laravel project, configured the database, created the migration and model, added routes, built the upload form, and validated the uploaded CSV file.
Now it's time to process the uploaded CSV file and save the records into the MySQL database.
After validating the uploaded file, retrieve it from the request.
$file = $request->file('csv_file');
Laravel stores the uploaded file temporarily, allowing you to access its path before processing it.
Next, open the CSV file using PHP's built-in fopen() function.
$handle = fopen($file->getRealPath(), "r");
The getRealPath() method returns the temporary file location on the server.
Using fopen() enables Laravel to read the CSV file one row at a time, which is memory-efficient even for moderately large files.
Most CSV files contain column headings such as:
Name,Email,Phone
Since these are not actual records, skip the first row before importing the data.
fgetcsv($handle);
This reads and ignores the first row, ensuring only the data rows are inserted into the database.
Now read every row in the CSV file.
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
}
The fgetcsv() function converts each row into an array.
For example, a CSV row like:
John Doe,john@example.com,9876543210
becomes
$row[0] // John Doe
$row[1] // john@example.com
$row[2] // 9876543210
This makes it easy to insert values into the database.
Inside the loop, create a new record using Laravel's Eloquent model.
User::create([
'name' => $row[0],
'email' => $row[1],
'phone' => $row[2]
]);
Because we already defined the $fillable property in the model, Laravel allows mass assignment safely.
Each row from the CSV file is inserted into the database as a new record.
Below is a simple example of the complete store() method.
public function store(Request $request)
{
$request->validate([
'csv_file' => 'required|mimes:csv,txt'
]);
$file = $request->file('csv_file');
$handle = fopen($file->getRealPath(), 'r');
fgetcsv($handle);
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
User::create([
'name' => $row[0],
'email' => $row[1],
'phone' => $row[2]
]);
}
fclose($handle);
return back()->with('success','CSV Imported Successfully');
}
This method is suitable for small and medium-sized CSV files.
After importing the data, show a confirmation message.
In your Blade file:
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
This provides immediate feedback to the user that the import was successful.
One common challenge during CSV imports is duplicate data. If users upload the same CSV file multiple times, duplicate records may be inserted into the database.
Laravel provides an elegant solution using updateOrCreate().
User::updateOrCreate(
[
'email'=>$row[1]
],
[
'name'=>$row[0],
'phone'=>$row[2]
]
);
This checks whether the email already exists.
If it exists, Laravel updates the existing record.
If it doesn't exist, Laravel creates a new one.
This approach keeps your database clean and avoids duplicate entries.
Sometimes a CSV file contains incomplete or invalid data.
For example:
Missing email address
Empty name
Invalid phone number
Before inserting a row, verify that the required fields are available.
Example:
if(empty($row[0]) || empty($row[1])){
continue;
}
Using continue skips invalid rows without stopping the import process.
This makes your application more reliable when handling user-uploaded files.
Unexpected issues such as malformed CSV files or database errors can interrupt the import process.
Wrap your import logic inside a try...catch block.
try{
// Import Code
}
catch(Exception $e){
return back()->with('error',$e->getMessage());
}
This ensures that errors are handled gracefully and meaningful messages are displayed to users instead of a blank error page.
When importing thousands of records, performance becomes important.
Here are some best practices:
Large files may take longer to process.
set_time_limit(300);
This allows the script to run for up to five minutes.
ini_set('memory_limit','512M');
This prevents memory exhaustion during large imports.
Instead of loading the entire CSV file into memory, process it row by row or in small batches.
Chunk processing reduces memory usage and improves stability.
Rather than inserting one row at a time, collect multiple rows into an array and insert them together.
Bulk inserts significantly improve performance for large datasets.
If users frequently upload CSV files containing tens of thousands of records, consider using Laravel Queues.
Queues allow the import to run in the background without making users wait for the request to finish.
This improves the overall user experience and keeps your application responsive.
CSV imports involve user-uploaded files, so security should always be a priority.
Follow these recommendations:
Accept only CSV or TXT file formats.
Validate all uploaded files.
Limit maximum upload size.
Skip invalid rows instead of crashing the import.
Escape unexpected characters when necessary.
Validate email addresses before insertion.
Use Laravel validation rules consistently.
Never trust user-uploaded data without verification.
These practices help protect your application from invalid data and potential security risks.
Many beginners encounter issues while implementing CSV imports.
Avoid these common mistakes:
Forgetting to skip the CSV header row.
Missing the @csrf token in the upload form.
Not defining $fillable in the model.
Importing duplicate records.
Ignoring validation before insertion.
Uploading Excel files without proper conversion to CSV.
Not closing the file using fclose().
Processing extremely large files without chunking or queues.
Assuming every CSV file follows the same column order.
Not providing user-friendly success or error messages.
By avoiding these mistakes, you'll build a more reliable and maintainable import feature.
Importing CSV files into a MySQL database using Laravel is a practical feature that saves time and improves productivity for businesses handling large amounts of data.
With Laravel's validation, Eloquent ORM, and file handling capabilities, you can create a secure and efficient import system with minimal code. By validating uploaded files, skipping invalid records, preventing duplicate entries, and optimizing performance for large datasets, your application can handle real-world import requirements confidently.
Whether you're building a CRM, inventory management system, HR portal, school management application, or eCommerce platform, a well-designed CSV import feature enhances usability and streamlines data management. Following Laravel best practices ensures your import process remains scalable, secure, and easy to maintain as your application grows.
Uploading a CSV file in Laravel is simple. Create a form with the multipart/form-data attribute, validate the uploaded file using Laravel's validation rules, and process it in a controller. Laravel's file handling features make uploading secure and efficient.
You can import CSV data by reading the uploaded file with PHP's fgetcsv() function or using a package like Laravel Excel. Loop through each row, validate the data, and insert it into the database using Laravel's Eloquent ORM.
Yes. Laravel can handle large CSV files by increasing the execution time and memory limit, processing records in chunks, or using Laravel Queues for background processing. These methods improve performance and prevent server timeouts.
Laravel provides methods like updateOrCreate() and firstOrCreate() to prevent duplicate records. You can check unique fields such as email, product code, or customer ID before inserting data into the database.
Laravel can import CSV, TXT, Excel (.xlsx), and other file formats depending on the libraries used. CSV is the most common because it is lightweight, easy to process, and supported by most applications.
Validation ensures that only valid and safe data enters your database. It helps prevent incorrect file formats, missing fields, duplicate records, and invalid values that could affect your application's performance and data integrity.
Yes. By using the Laravel Excel package (Maatwebsite Excel), you can import Excel files such as .xlsx and .xls directly without converting them into CSV format.
The most popular package is Laravel Excel (Maatwebsite Excel). It provides advanced features such as chunk reading, queued imports, validation, exporting data, and support for Excel and CSV file formats.
After completing the import, redirect the user back with a success session message.
Example:
return back()->with('success', 'CSV Imported Successfully');
You can display this message in your Blade template using Laravel's session helper.
Before inserting each record, check whether the required columns contain data. If a row is empty or incomplete, use the continue statement to skip it and proceed with the next record.
Request a FREE Business Plan.
+91 ▼
In the modern business landscape, companies—regardless of size—are striving to optimize operations, enhance employee satisfaction, and ensure compliance with labor laws. One area that sign
Read More
Cracking Trivago: Revolutionising Trip Arranging The process of organizing a holiday has changed dramatically in the modern era. Travel arrangements used to be made by going to travel age
Read More
In today’s fast-paced travel industry, efficiency, accuracy, and user satisfaction are paramount. Businesses—especially travel agencies, tour operators, and corporate travel departments&md
Read More