How To Import and Export Excel and CSV File In Laravel 11

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
How To Import and Export Excel and CSV File In Laravel 11

Welcome To ITSolutionsGuides,


In this it solutions guides tutorial we will see How To Import and Export Excel and CSV File In Laravel 11 using the maatwebsite/excel composer package. By using the maatwebsite/excel package we can import any excel or csv file through a input field and the store the data from the file in the database and also we can export the data from the database to any desired excel or csv formats. maatwebsite/excel package provide file exporting options with the extensions .csv, .xls, and .xlsx .

To use the maatwebsite/excel composer package for import and export we need to
install the maatwebsite/excel composer package
then we should create import class for importing the excel or csv data
then we should create export class for exporting the database data into excel or csv file

Lets see with an example,

Let's Start Coding

Lets install a new laravel application and the we need to install the maatwebsite/excel package using the composer since we are using the maatwebsite/excel package for importing and exporting the data in the excel and csv file.

composer require maatwebsite/excel

Let's Generate Dummy Records

Lets generate dummy user records using the factory tinker using the following command,

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

Let's Create Import Class

Lets create the import class using the following artisan command using the flag --model={model name} the model name is provided to create class for the specific model,
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:5',
            'email' => 'required|email|unique:users'
        ];
    }
}

Let's Create Export Class

Lets create the export class using the following artisan command using the flag --model={model name} the model name is provided to create class for the specific model,
php artisan make:export UsersExport --model=User
In this export class we will select the colulmn name that should get exported as the excel or csv file.


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"];
    }
}

Let's Create Controller

Lets create the controller using the following artisan command,
php artisan make:controller UserController
Lets create the two function for both import and export the in excel or csv file by using Excel::download() and Excel::import() for importing and exporting the data.


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) 
    {
        // Validate incoming request data
        $request->validate([
            'file' => 'required|max:2048',
        ]);
  
        Excel::import(new UsersImport, $request->file('file'));
                 
        return back()->with('success', 'Users imported successfully.');
    }
}

Let's Create Routes

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');

Let's Create Blade File

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Import and Export Excel and CSV File In Laravel 11</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 and Export Excel and CSV File In Laravel 11</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>

Let's Run Laravel Application

Lets run the laravel application using the following artisan command,

php artisan serve

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides