How to Import Export Excel and CSV File in Laravel 9 ?

Today now in this post i will show you How to Import Export Excel and CSV File in Laravel 9 ? Here I am going to show you a full example of import export excel in laravel 9. Now in this tutorial i will give you a very simple example of laravel 9 import export csv file. Here we will look at an example of how to import export csv file in laravel 9 application. Now in this article i will give you a very simple example of laravel 9 import file in excel format.

Here i will use maatwebsite/excel composer package for the import and export tasks in laravel application. Now in this example, i will create a very simple form for the input where we can upload any csv file and create the multiple users. Then we will also create an export route that will be download all the users from the database in excel file.

So, let’s need to follow the below step to create the import and export function in laravel 9 application. We can export the file with .csv, .xls and .xlsx file.

Step 1: Install Laravel 9

This is first step. This step is not needed if you already install this in previous. However, if you don’t have then need to created the laravel application, then we can create by using the below command:

composer create-project laravel/laravel example-app
Step 2: Install maatwebsite/excel Package

Now in this step we have to install the maatwebsite/excel package by using the Composer package manager, so need to open your terminal and then fire the bellow command:

composer require psr/simple-cache:^1.0 maatwebsite/excel

If, we are using the less the laravel 9 versions then need to use the bellow command:

composer require maatwebsite/excel
Step 3: Create Dummy Records

Now in this step, i will store the some dummy records for the users table, so that we can export them with that users. So let’s need to run the bellow tinker command:

php artisan tinker  
User::factory()->count(10)->create()
Step 4: Create Import Class

Now in maatwebsite 3 version is provide the way to built the import class and we need to use in the controller. So it would be great way to create the new Import class. So we need to run the following command and then change the following code on that file:

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 Hash;
  
class UsersImport implements ToModel, WithHeadingRow
{
    /**
    * @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']),
        ]);
    }
}
Step 5: Create Export Class

In maatwebsite 3 version is also provide a way to built the export class and we need to use the controller. So it will be also a great way to create a new Export class. So we need to run the following command and need to change the following code on that file:

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

Now in this step, i will create a controller as name UserController with the index(), export() and import() method. So at first let’s create the controller by the following command and need to update code on it.

php artisan make:controller UserController

Now, need to update the code on UserController file.

app/Http/Controllers/UserController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
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() 
    {
        Excel::import(new UsersImport,request()->file('file'));
               
        return back();
    }
}

Step 7: Create Routes

Now in this step, we have to create the routes for the list of users, also import users and also export users. So need to open our “routes/web.php” file and then add the following route.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::controller(UserController::class)->group(function(){
    Route::get('users', 'index');
    Route::get('users-export', 'export')->name('users.export');
    Route::post('users-import', 'import')->name('users.import');
});

Step 8: Create Blade File

Now we are in the Last step, let’s need to create users.blade.php(resources/views/users.blade.php) for the layout and i will write the design code here and then put the following code:

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Import Export Excel to Database Example - CodingsPoint.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
     
<div class="container">
    <div class="card bg-light mt-3">
        <div class="card-header">
            Laravel 9 Import Export Excel to Database Example - CodingsPoint.com
        </div>
        <div class="card-body">
            <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">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') }}">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>

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →