Automation Testing Company in India
The world is heading towards automation, it has it’s strong footsteps in Software testing as well. We at Blazingcoders perform automation testing with various tools such as Junit, Selenium, QTP/
Read MoreSign Up Now and Get FREE CTO-level Consultation.
In today’s data-driven world, managing large amounts of data efficiently is crucial. Whether you are building an admin dashboard, an analytics tool, or a simple content management system, the ability to import CSV (Comma-Separated Values) files into your Laravel-based application can save time and improve productivity. This blog walks you through the complete process of uploading CSV files and importing their contents into a database using Laravel PHP.
CSV files are widely used for data exchange between systems. They are lightweight, easy to create, and compatible with many tools. In Laravel, handling file uploads and processing data is seamless thanks to its robust features and support for third-party packages.
Easy data migration
Bulk upload of records
Integration with spreadsheets and reports
Support for background processing
Let’s dive into a step-by-step implementation of how to upload and import CSV data into a database using Laravel.
If you don’t already have a Laravel project, create one using Composer:
composer create-project --prefer-dist laravel/laravel csv-importer |
Then navigate into your project directory:
cd csv-importer |
Assume we’re importing users. Run the following Artisan commands:
php artisan make:model User -m |
Edit the migration file in database/migrations/xxxx_xx_xx_create_users_table.php
:
public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); } |
Create a route and view to upload the CSV file.
In routes/web.php
:
use App\Http\Controllers\CSVImportController;
Route::get('/upload-csv', [CSVImportController::class, 'showForm'])->name('csv.form'); |
Create a controller:
php artisan make:controller CSVImportController |
In resources/views/csv_form.blade.php
:
Edit CSVImportController.php
:
namespace App\Http\Controllers; use Illuminate\Http\Request; class CSVImportController extends Controller public function uploadCSV(Request $request) $file = fopen($request->file('csv_file'), 'r'); while (($data = fgetcsv($file, 1000, ',')) !== FALSE) { fclose($file); return redirect()->back()->with('success', 'CSV Data Imported Successfully.'); |
Make sure User.php
has fillable
properties defined:
protected $fillable = ['name', 'email']; |
Create a sample users.csv
file:
name,email John Doe,john@example.com Jane Smith,jane@example.com |
Visit http://localhost:8000/upload-csv
Upload the CSV file
Check your database; users should be imported!
To avoid issues with duplicate or invalid data, improve validation before inserting:
if (filter_var($data[1], FILTER_VALIDATE_EMAIL)) { if (!User::where('email', $data[1])->exists()) { User::create([ 'name' => $data[0], 'email' => $data[1], ]); } } |
If your CSV files are large or you need advanced features, use Laravel Excel:
composer require maatwebsite/excel |
php artisan make:import UsersImport --model=User |
app/Imports/UsersImport.php
: namespace App\Imports; use App\Models\User; class UsersImport implements ToModel |
use App\Imports\UsersImport; public function uploadCSV(Request $request) Excel::import(new UsersImport, $request->file('csv_file')); return back()->with('success', 'Data Imported Successfully using Laravel Excel.'); |
Uploading CSV files and importing them into the database is a common requirement in many Laravel applications. Whether it's user data, product lists, or any bulk data entry scenario, Laravel provides powerful tools and clean syntax to make it easy.
If you're working with small to medium datasets, the built-in PHP functions like fgetcsv()
work well. For more advanced or large-scale imports, Laravel Excel offers a full-featured solution including chunking, queueing, and validation.
Now you can try this code in your application to read CSV files and import to the database the same method you can use in other PHP related frameworks also.
1) How do I import a CSV file into a Laravel database?
You can import a CSV in Laravel by reading the file using fgetcsv()
, then looping through its rows and inserting data using Eloquent models.
2) What is the best way to upload and read CSV files in Laravel?
Use a file upload form, validate the file type, read it using PHP functions like fopen()
and fgetcsv()
, then insert rows into the database.
3) How can I validate a CSV file in Laravel?
Use Laravel’s file validation rule:
'csv_file' => 'required|mimes:csv,txt|max:2048'
This ensures only valid CSV or TXT files are accepted.
4) Can I use Laravel Excel to import CSV files?
Yes, Laravel Excel (maatwebsite/excel
) is a powerful package that supports importing and exporting CSV or Excel files efficiently with queue support.
5) Why is my CSV import not working in Laravel?
Common issues include wrong file format, incorrect CSV headers, model fillable settings, or file not readable by PHP.
6) Is it safe to upload CSV files to Laravel?
Yes, if you validate the file type, sanitize data, limit file size, and prevent script execution from uploaded files, it is secure.
7) How do I skip the header row while reading a CSV file in Laravel?
Use fgetcsv($file)
once before the loop to skip the header row.
Request a FREE Business Plan.
The world is heading towards automation, it has it’s strong footsteps in Software testing as well. We at Blazingcoders perform automation testing with various tools such as Junit, Selenium, QTP/
Read MoreParents and students today are quite picky when selecting the best university. Campus tours and pamphlets are great indicators of an institution's caliber. Nevertheless, the most comprehensive sou
Read MoreHire Web Developers & Web Designers Chennai To stay competitive in the digital age, companies need to have strong and easy-to-use websites. Professional web developers and designers turn to Bla
Read More