Join WhatsApp ChannelJoin Now

Laravel 8 Import Export Excel File

Hello Dev,

Today, i we will show you laravel 8 import export excel file. This article will give you simple example of laravel 8 import export excel file. you will learn laravel 8 import export excel file. So let’s follow few step to create example of laravel 8 import export excel file.

Laravel 8 Import Export Excel File

Step 1:- Install Laravel 8

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

Connect Database .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=databse
DB_USERNAME=root
DB_PASSWORD=

Step 2:- Install maatwebsite/excel Package

composer require maatwebsite/excel

Now open config/app.php file and add service provider and aliase.
config/app.php

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

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

Then just migrate it by using following command

php artisan migrate

Step 3 :- Create Authentication

composer require laravel/ui

php artisan ui bootstrap --auth

Step 4: Create Dummy Users

php artisan tinker
\App\Models\User::factory(10)->create();

Step 5:- Add Routes

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\MyController;

/*
|--------------------------------------------------------------------------
| 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::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');


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

Step 6:- Create Import Class

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;
     
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 7:- Create Export Class

php artisan make:export UsersExport --model=User

app/Exports/UsersExport.php

<?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 8:- Add Controller

app/Http/Controllers/MyController.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 MyController extends Controller
{

    public function index()
    {
       return view('import');
    }
    
    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 8');
    }
	
    public function exportExcelCSV($slug) 
    {
        return Excel::download(new UsersExport, 'users.'.$slug);
    }
}

Step 9:- Create Blade File

resources/views/import.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Import Export Excel File - codeplaners.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">Laravel 8 Import Export Excel File - codeplaners.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>

Now we are ready to run our project.

php artisan serve
http://localhost:8000/excel-csv-file

Download Source Code

Recommended Posts