Upload CSV files and import to Database using Laravel PHP
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.
Why Use CSV File Upload in Laravel?
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.
Key Benefits:
Let’s dive into a step-by-step implementation of how to upload and import CSV data into a database using Laravel.
Step 1: Set Up Your Laravel Project
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:
Step 2: Create a Migration and Model
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(); }); } |
Step 3: Create the File Upload Form
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'); Route::post('/upload-csv', [CSVImportController::class, 'uploadCSV'])->name('csv.upload'); |
Create a controller:
php artisan make:controller CSVImportController |
In resources/views/csv_form.blade.php
:
Step 4: Handle the File Upload and Data Import
Edit CSVImportController.php
:
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class CSVImportController extends Controller { public function showForm() { return view('csv_form'); } public function uploadCSV(Request $request) { $request->validate([ 'csv_file' => 'required|file|mimes:csv,txt' ]); $file = fopen($request->file('csv_file'), 'r'); $firstline = true; while (($data = fgetcsv($file, 1000, ',')) !== FALSE) { if (!$firstline) { User::create([ 'name' => $data[0], 'email' => $data[1], ]); } $firstline = false; } fclose($file); return redirect()->back()->with('success', 'CSV Data Imported Successfully.'); } } |
Make sure User.php
has fillable
properties defined:
protected $fillable = ['name', 'email']; |
Step 5: Test the CSV Import
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!
Step 6: Error Handling and Validation
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], ]); } } |
Step 7: Use Laravel Excel for Large Files (Optional)
If your CSV files are large or you need advanced features, use Laravel Excel:
Install via Composer:
composer require maatwebsite/excel |
Create an Import Class:
php artisan make:import UsersImport --model=User |
In app/Imports/UsersImport.php
:
namespace App\Imports; use App\Models\User; use Maatwebsite\Excel\Concerns\ToModel; class UsersImport implements ToModel { public function model(array $row) { return new User([ 'name' => $row[0], 'email' => $row[1], ]); } } |
Update Controller:
use App\Imports\UsersImport; use Maatwebsite\Excel\Facades\Excel; public function uploadCSV(Request $request) { $request->validate([ 'csv_file' => 'required|file|mimes:csv,txt,xlsx' ]); Excel::import(new UsersImport, $request->file('csv_file')); return back()->with('success', 'Data Imported Successfully using Laravel Excel.'); } |
Final Thoughts
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.