Import Export Excel and CSV File using LARAVEL 10

Spread the love

Hello, Guys.

In this concise tutorial, we will explore the process of Importing and Exporting Excel and CSV Files in Laravel 10 with building the Import Export Excel and CSV File

If you are seeking guidance on how to perform CSV import and export operations in Laravel 10, you have arrived at the perfect resource. We will be using the maatwebsite/excel composer package to streamline these tasks.

To begin, I will guide you through the creation of a straightforward input form. This form will enable you to effortlessly upload CSV files and generate multiple user entries in your Laravel 10 application.

Let’s proceed with building the Import Export Excel and CSV File functionality within your Laravel 10 application by following these steps. Notably, this functionality allows you to export files in various formats, including .csv, .xls, and .xlsx files. It’s a valuable addition to your Laravel toolkit for managing data efficiently.

Step 1: Install Laravel 10 for Import Export Excel and CSV File

While not obligatory, you may proceed to execute the following command if you haven’t yet established your Laravel application:

Also Read: How to Create Custom Helper Functions in LARAVEL 10

composer create-project laravel/laravel example-app

Step 2: Install maatwebsite/excel Package

To successfully proceed with this step, you need to install the “maatwebsite/excel” package via the Composer package manager. Simply open your terminal and enter the following command:

composer require maatwebsite/excel

Step 3: Create Dummy Records

To export the users table with its associated user data, we’ll begin by creating placeholder records. To accomplish this, we can run the following Tinker command:

php artisan tinker

User::factory()->count(10)->create()

Step 4: Create Import Class

The Maatwebsite 3rd version introduces a convenient method for generating import classes that are essential for controller usage. This is a highly recommended approach for building new import classes. To get started, it’s important to execute the following command and make the necessary code modifications within the specified file:

php artisan make:import UsersImport --model=User
app/Imports/UsersImport.php

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

<?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

Creating a new Export class is an excellent approach to enhance your project. To get started, execute the command provided below, and make the necessary code adjustments within the specified 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

During this stage, we’ll create a UserController with the essential methods: index(), export(), and import(). To start building the controller, execute the provided command below, and proceed to make the necessary code adjustments.

Also Read: How to Rollback Migration in Laravel?

php artisan make:controller UserController

Immediate Code Update Required for the 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

In this step, you’ll want to establish routes for user lists, user imports, and user exports. To achieve this, insert the following route into your “routes/web.php” file.

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

Let’s create the users.blade.php file located at resources/views/users.blade.php as part of the final phase layout development. In this step, we will craft the design code and include the following lines of code:

Also Read: how to Create Custom Artisan Command in LARAVEL

resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Import Export Excel to Database Example - itcodestuff.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 to Database Example - itcodestuff.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>

Run Laravel App:

After completing all necessary steps, you must now input the command listed below and press Enter to launch the Laravel application:

Also Read: How To Create Repeater Field Using Bootstrap

php artisan serve

Now, Enter the provided URL into your web browser to view the app’s output.

http://localhost:8000/users

Your quest for the best Laravel blog ends here, where expert knowledge meets curated excellence.

Leave a Comment