How to Import Export CSV and Excel File in Laravel 11

In this article, we'll see how to import and export CSV and Excel files in laravel 11. Here, we'll learn about how to import CSV/Excel files in laravel 11 and how to export CSV/Excel in laravel 11. I will use the maatwebsite/excel composer package for import and export tasks.

In this example, I will create a simple form for input where users can upload a CSV file and create multiple users. Then, I will create an export route that will download all users from the database in an Excel file.

Follow the steps below to create the import and export function in a Laravel 11 application. Files can be exported with .csv, .xls, and .xlsx extensions.

So, let's see laravel 11 import export CSV and Excel files, how to import CSV Excel files in laravel 11 using maatwebsite/excel, and export CSV Excel files in laravel 11.

Step 1: Install Laravel 11

In the first step, we'll install laravel 11 using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Install maatwebsite/excel Package

After that, we'll install maatwebsite/excel package using the following command.

composer require maatwebsite/excel

 

Step 3: Create Dummy Records

Then, we'll create some dummy records using the tinker command.

php artisan tinker
  
User::factory()->count(50)->create()

 

Step 4: Create Import Class

Now, create a new Import class using the following command. For example, let's name it UsersImport.

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.php

<?php
  
namespace App\Imports;
  
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Hash;
  
class UsersImport implements ToModel, WithHeadingRow, WithValidation
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'name'     => $row['name'],
            'email'    => $row['email'], 
            'password' => Hash::make($row['password']),
        ]);
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function rules(): array
    {
        return [
            'name' => 'required',
            'password' => 'required|min:6',
            'email' => 'required|email|unique:users'
        ];
    }
}

File Example:

name email password
abc abc@test.com 123456

 

Step 5: Create Export Class

After that, we'll create a new Export class using the following command. For example, let's name it UsersExport.

php artisan make:export UsersExport --model=User

app/Exports/UsersExport.php

<?php
  
namespace App\Exports;
    
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
    
class UsersExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::select("id", "name", "email")->get();
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function headings(): array
    {
        return ["ID", "Name", "Email"];
    }
}
 
Step 6: Create Controller

In this step, I will create a UserController with index(), export(), and import() methods. So, run the following command to create a controller.

php artisan make:controller UserController

app/Http/Controllers/UserController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use App\Models\User;
    
class UserController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function index()
    {
        $users = User::get();
  
        return view('users', compact('users'));
    }
          
    /**
    * @return \Illuminate\Support\Collection
    */
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
         
    /**
    * @return \Illuminate\Support\Collection
    */
    public function import(Request $request) 
    {
        $request->validate([
            'file' => 'required|max:2048',
        ]);
  
        Excel::import(new UsersImport, $request->file('file'));
                 
        return back()->with('success', 'Users imported successfully.');
    }
}
 
Step 7: Create Routes

Now, we'll create routes into the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
Route::get('users', [UserController::class, 'index']);
Route::get('users/export', [UserController::class, 'export'])->name('users.export');
Route::post('users/import', [UserController::class, 'import'])->name('users.import');

 

Step 8: Create Blade File

In this step, we'll create users.blade.php file. and add the HTML layout for importing and exporting CSV and Excel files in laravel 11.

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Import Export CSV and Excel File in Laravel 11 - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
      
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> How to Import Export CSV and Excel File in Laravel 11 - Techsolutionstuff</h3>
        <div class="card-body">
  
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
            @endsession
  
            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
  
            <form action="{{ route('users.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
  
                <input type="file" name="file" class="form-control">

                <br>
                <button class="btn btn-success"><i class="fa fa-file"></i> Import User Data</button>
            </form>
    
            <table class="table table-bordered mt-3">
                <tr>
                    <th colspan="3">
                        List Of Users
                        <a class="btn btn-warning float-end" href="{{ route('users.export') }}"><i class="fa fa-download"></i> Export User Data</a>
                    </th>
                </tr>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
                @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
                @endforeach
            </table>
    
        </div>
    </div>
</div>
       
</body>
</html>
 
Step 9: Run Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


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