Laravel 11 Import Export CSV and Excel File

Websolutionstuff | Sep-13-2024 | Categories : Laravel

Hello, Laravel developers! In this article, I'll show you how to easily import and export CSV and Excel files in Laravel 11. We'll walk through the steps to import data from a CSV or Excel file and also how to export data back into these formats. I'll be using the maatwebsite/excel package to handle these tasks.

In this example, I'll create a simple form where users can upload a CSV file to add multiple users to the database. Then, I'll set up an export route that allows you to download all users from the database as an Excel file.

You can be exported with .csv, .xls, and .xlsx extensions. How to import CSV Excel files in laravel 11 using maatwebsite/excel.

Laravel 11 Import Export CSV and Excel File

 

Step 1: Install Laravel 11

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

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

 

Step 2: Install maatwebsite/excel Package

Then, we'll install maatwebsite/excel composer 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 [email protected] 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>Laravel 11 Import Export CSV and Excel File - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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> Laravel 11 Import Export CSV and Excel File - Websolutionstuff</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:

Recommended Post
Featured Post
Laravel 9 Flash Message Example
Laravel 9 Flash Message Exampl...

In this article, we will see a laravel 9 flash message example. Here, we will learn how to create or implement flash mes...

Read More

Dec-27-2022

How To Create Dynamic Pie Chart In Laravel
How To Create Dynamic Pie Char...

In this article, we will see how to create a dynamic pie chart in laravel. charts are used to represent data i...

Read More

Jun-24-2020

Laravel 9 Group By Query Example
Laravel 9 Group By Query Examp...

In this article, we will see laravel 9 group by query example. how to use group by in laravel 9. As you might expec...

Read More

Mar-29-2022

How to Generate Avatar Image for User in Laravel 11
How to Generate Avatar Image f...

Creating avatar images for users in Laravel 11 can enhance the visual appeal of your application and make it more person...

Read More

Jan-16-2025