Laravel - Import CSV

version : Laravel 10
Post Time : 30-06-2024

Import CSV

install laravel
       - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo
       - cd laravel_demo
       - composer require phpoffice/phpspreadsheet

Create DemoController Controller  :
          - php artisan make:controller DemoController

app/Http/Controllers/DemoController.php

                                      
                                        

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Models\Customer;

class DemoController extends Controller
{
   public function CSVDemo(Request $request)
   {
       return view('csv_demo');
   }

   public function importCSV(Request $request)
   {
       $request->validate([
           'csv_file' => 'required|mimes:csv,txt',
       ]);

       $file = $request->file('csv_file');
       $spreadsheet = IOFactory::load($file->getPathname());
       $sheet = $spreadsheet->getActiveSheet();

       $row_data = [];
       foreach ($sheet->getRowIterator() as $row) {
           $cellIterator = $row->getCellIterator();
           $cellIterator->setIterateOnlyExistingCells(false); // Loop through all cells, even if a cell value is not set
           $row_info = [];
           foreach ($cellIterator as $cell) {
               $row_info[] = $cell->getValue();
           }
           $row_data[] = $row_info;
       }

       foreach ($row_data as $index => $value) {
           if ($index === 0) {
               // Skip the header row
               continue;
           }
           Customer::create([
               'name' => $value[0],
               'email' => $value[1],
               'address' => $value[2],
               'phone_no' => $value[3],
           ]);
       }
       return redirect()->back()->with('success', 'CSV successfully imported.');
   }
}

Create Customer Model:
          - php artisan make:model Customer
app/Models/Customer.php

                                      
                                        

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
   use HasFactory;

   protected $fillable = [
       'name',
       'email',
       'address',
       'phone_no'
   ];
}

Create csv_demo blade file :-
Resources/views/csv_demo.blade.php

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
   <style>
       .error{
           color:red;
       }
   </style>
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>Import CSV</h1>
   </div>
   <form action="{{ route('importCSV') }}" method="POST" enctype="multipart/form-data">
       @csrf
       @if(Session::has('error'))
           <div class="alert alert-danger" id="success-alert">
               {{Session::get('error')}}
           </div>
       @endif
       @if(Session::has('success'))
           <div class="alert alert-success" id="success-alert">
               {{Session::get('success')}}
           </div>
       @endif
       <div class="mb-3 row text-center">
           <label class="col-md-12 col-form-label text-center">Upload CSV : </label>
           <div class="mb-3 mt-4 row" style="display:flrx; justify-content:center;">
               <div class="col-md-6">
                   <input id="csv_file" type="file" name="csv_file" class="form-control">
                   @error('csv_file')
                       <label class="error">{{ $message }}</label>
                   @enderror
               </div>
           </div>
           <div class="mb-3 mt-4 row text-center">
               <div class="col-sm-12">
                   <button type="submit" class="btn btn-primary">Save</button>
               </div>
           </div>
       </div>
   </form>
</body>
</html>

routes/web.php

                                      
                                        

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/csv_demo', [DemoController::class, 'CSVDemo'])->name('CSVDemo');
Route::post('/import_csv', [DemoController::class, 'importCSV'])->name('importCSV');


Sample CSV file :-