Saturday, September 21, 2024
Google search engine
HomeLanguagesLaravel 9 Import Export Excel & CSV File using maatwebsite/excel

Laravel 9 Import Export Excel & CSV File using maatwebsite/excel

Laravel 9 import export excel, csv file example; In this tutorial, we would love to show you how to import and export excel & csv files to the database in laravel 9 using maatwebsite/excel package.

Laravel 9 Import Export Excel & CSV File using maatwebsite/excel

Follow the following steps to import-export CSV and excel file in laravel 9 apps:

  • Step 1 – Setup Laravel 9 Application
  • Step 2 – Database Configuration
  • Step 3 – Install maatwebsite/excel Package
  • Step 4 – Configure maatwebsite/excel
  • Step 5 – Create Routes
  • Step 6 – Compose Import Export Class
  • Step 7 – Create ExcelCSV Controller By Artisan Command
  • Step 8 – Create Import Export Form
  • Step 9 – Run Development Server

Step 1 – Setup Laravel 9 Application

First of all download or install laravel 9 new setups. So, open the terminal and type the following command to install the new laravel 9 app into your machine:

composer create-project --prefer-dist laravel/laravel ExcelCSVImportExport

Step 2 – Database Configuration

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like the following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Install maatwebsite/excel Package

Installing maatwebsite/excel package using the following command:

composer require maatwebsite/excel

Step 4 – Configure maatwebsite/excel

Configure maatwebsite/excel package in the app.php file. Open the app.php file, which is established inside the config directory.

'providers' => [
  .......
  .......
  .......
  Maatwebsite\Excel\ExcelServiceProvider::class,
 
 ],  

'aliases' => [ 
  .......
  .......
  .......
  'Excel' => Maatwebsite\Excel\Facades\Excel::class,

], 

Then publish the config of maatwebsite/excel package by using the following command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Step 5 – Create Routes

Open web.php file from routes direcotry. And update the following routes into web.php file:

use App\Http\Controllers\ExcelCSVController;

Route::get('excel-csv-file', [ExcelCSVController::class, 'index']);
Route::post('import-excel-csv-file', [ExcelCSVController::class, 'importExcelCSV']);
Route::get('export-excel-csv-file/{slug}', [ExcelCSVController::class, 'exportExcelCSV']);

Step 6 – Compose Import Export Class

Create import and export excel csv class using the following commands:

For compose import class:

php artisan make:import UsersImport --model=User

Then update the following code into UsersImport.php class file, which is established at app/Imports directory:

<?php
   
namespace App\Imports;
   
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
    
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']),
        ]);
    }
}

For compose export class:

php artisan make:export UsersExport --model=User

Then update the following code into UsersImport.php class file, which is established at app/Exports directory:

<?php
  
namespace App\Exports;
  
use App\Models\User;

use Maatwebsite\Excel\Concerns\FromCollection;
  
class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}

Step 7 – Create ExcelCSV Controller By Artisan Command

Create ExcelCSV controller by using the following command:

php artisan make:controller ExcelCSVController

After that, go to app/http/controllers and open ExcelCSVController.php file. And update the following code into it:

<?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 ExcelCSVController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function index()
    {
       return view('excel-csv-import');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function importExcelCSV(Request $request) 
    {
    	$validatedData = $request->validate([

           'file' => 'required',

        ]);

        Excel::import(new UsersImport,$request->file('file'));

           
        return redirect('excel-csv-file')->with('status', 'The file has been excel/csv imported to database in laravel 9');
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function exportExcelCSV($slug) 
    {
        return Excel::download(new UsersExport, 'users.'.$slug);
    }
   
}

Step 8 – Create Blade File

Create blade view file for import export excel and csv file from database. So, Go to resources/views directory and create excel-csv-import.blade.php and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 Import Export Excel and CSV File To Database Example Tutorial - Tutsmake.com</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-5">

  
  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">

    <div class="card-header font-weight-bold">
      <h2 class="float-left">Import Export Excel, CSV File In Laravel 9 - Tutsmake.com</h2>
      <h2 class="float-right"><a href="{{url('export-excel-csv-file/xlsx')}}" class="btn btn-success mr-1">Export Excel</a><a href="{{url('export-excel-csv-file/csv')}}" class="btn btn-success">Export CSV</a></h2>
    </div>

    <div class="card-body">

        <form id="excel-csv-import-form" method="POST"  action="{{ url('import-excel-csv-file') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="file" placeholder="Choose file">
                    </div>
                    @error('file')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>              
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div>  
</body>
</html>

Step 9 – Run Development Server

Execute the following command on command prompt to start the development server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/excel-csv-file

Recommended Laravel Tutorials

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments