How to Import CSV File in Laravel 10 using League/csv

Hey there! Today, I'm excited to share a quick guide on how to import CSV files into your Laravel application using the handy league/csv package. Importing CSVs can be super useful when you have a bunch of data you want to bring into your Laravel project without the hassle.

In this walkthrough, I'll show you step by step how to set up a CSV import feature. We'll use the CsvImportController to handle the heavy lifting and make things as smooth as possible.

In this article, we'll see how to import CSV files using league/csv in Laravel 8, Laravel 9, and Laravel 10.

So, if you've got a CSV file that's begging to be part of your database, let's dive in and get it done! 🚀

 Here's a step-by-step guide on how to import a CSV file using league/csv in Laravel:

Step 1: Install Laravel

If you haven't already, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel laravel-10-league-csv-import
cd laravel-10-league-csv-import

 

Step 2: Install league/csv Package

If you haven't installed the league/csv package yet, you can do so using Composer. Open a terminal and run the following command:

composer require league/csv

 

Step 3: Create a Controller

Create a controller that will handle the CSV import. You can use Artisan to generate a new controller:

php artisan make:controller CsvImportController

 

Step 4: Modify the Controller

Open the generated controller (CsvImportController.php) in your preferred code editor and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use League\Csv\Reader;
use App\Models\User;

class CsvImportController extends Controller
{
    public function import(Request $request)
    {
        // Validate the uploaded file
        $request->validate([
            'csv_file' => 'required|mimes:csv,txt',
        ]);

        // Get the uploaded file
        $file = $request->file('csv_file')->getPathname();

        // Create a CSV reader instance
        $csv = Reader::createFromPath($file, 'r');

        // Get all records from the CSV
        $records = $csv->getRecords();

        // Process and store each record in the database
        foreach ($records as $record) {
            User::create([
                'name' => $record['name'],
                'email' => $record['email'],
                'phone' => $record['phone'],
            ]);
        }

        // Redirect or return a response based on your needs
        return redirect()->back()->with('success', 'CSV file imported and data stored in the database.');
    }
}

 

Step 5: Define a Route

Open the routes/web.php file and add a route to your CSV import controller:

// routes/web.php

use App\Http\Controllers\CsvImportController;

Route::get('/import-form', function () {
    return view('csv-import-form');
});

Route::post('/import-csv', [CsvImportController::class, 'import']);

 

Step 6: Create a Form

Create a form in your view to allow users to upload a CSV file. For example:

resources/views/csv-import-form.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to import csv file using league/csv in laravel 10 - techsolutionstuff.com</title>
</head>
<body>

    @if(session('success'))
        <p>{{ session('success') }}</p>
    @endif
    <h3>How to import csv file in laravel 10 using league/csv - techsolutionstuff.com</h3>
    <form action="{{ url('/import-csv') }}" method="post" enctype="multipart/form-data">
        @csrf
        <label for="csv_file">Choose a CSV file:</label>
        <input type="file" name="csv_file" accept=".csv">
        <button type="submit">Import CSV</button>
    </form>

</body>
</html>

 
Step 7: Test the Export

Run your Laravel development server:

php artisan serve

 

Conclusion:

In conclusion, setting up a CSV import feature in my Laravel application using the league/csv package was a breeze. Laravel's flexibility, combined with the power of the league/csv package, made the entire process straightforward.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS