Laravel 10 Import Export Excel and CSV File Example Tutorial

Jun 11, 2024 | Laravel 10 Laravel


Hello Dev,

In this brief tutorial, we'll explore Laravel 10's import and export functionality for Excel files. I'll guide you through importing and exporting CSV files in Laravel 10 using the maatwebsite/excel Composer package. If you're looking for an example of importing and exporting CSV files in Laravel 10, you're in the right place.

We'll utilize the maatwebsite/excel Composer package for handling import and export tasks. In this example, we'll create a simple form where you can upload a CSV file to create multiple users. Additionally, we'll create an export route that will download all users from the database in an Excel file.

Let's proceed with the following steps to implement the import and export functionality in your Laravel 10 application. You'll be able to export files in formats such as .csv, .xls, and .xlsx.

Step 1: Install Laravel 11

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

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

In this step, we'll install the maatwebsite/excel package via the Composer package manager. Open your terminal and execute the following command:

composer require maatwebsite/excel
Step 3: Create Dummy Records

In this step, we'll create some dummy records for the users table so we can export them later. Let's run the following Tinker command:

php artisan tinker
User::factory()->count(10)->create()
Read Also: How to Upload Image Using Ajax in Laravel 10? Step 4: Create Import Class

In Maatwebsite version 3, it's advisable to create a dedicated import class and utilize it in the controller. Let's generate a new Import class by running the following command and then make the necessary changes to the generated 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 version 3, it's recommended to create a dedicated export class and use it in the controller. Let's generate a new Export class by running the following command and then make the necessary changes to the generated 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

In this step, we'll create a UserController with the index(), export(), and import() methods. Let's create the controller using the following command and then update the code accordingly:

php artisan make:controller UserController

Now, update 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();
    }
}
Read Also: Laravel 10 Ajax Form Submit With Validation Example Tutorial Step 7: Create Routes

In this step, we'll create routes for listing users, importing users, and exporting users. Open your "routes/web.php" file and add the following routes:

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

In the final step, let's create the users.blade.php file (located at resources/views/users.blade.php) for the layout. We'll write the design code here. Paste the following code into the users.blade.php file:

resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Import Export Excel and CSV File Example Tutorial -- ItErrorSolution.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 10 Import Export Excel and CSV File Example Tutorial -- ItErrorSolution.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>
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/users
Output:
Laravel 10 Import Export Excel and CSV File Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 10
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"