Import Export Excel & Csv to Database in Laravel Example

Import Export Excel & Csv to Database in Laravel Example

In this article, we will show how to import export excel data from database in laravel Framework using maatwebsite version 3 package with example. There have been many new changes in version 3 of the new maatwebsite package. It has made very simple and easy to use with laravel application for import export data to database. It will work with laravel version like 5.8, 5.7 .

For some time we want to export or import thousands of records to our database.Maatwebsite offers many features for exporting & importing thousands of records in excel sheet.

Contents

  • Install Laravel Fresh Project
  • Install Maatwebsite Package
  • Add Fake Records In Database
  • Create Controller
  • Add Routes
  • Create Import Export Classes
  • Create Blade View
  • Start Development Server
  • Conclusion

Install Laravel Fresh Project

We need to install Laravel fresh application using below command, Open your command prompt and run the below command :

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

After successfully install laravel 5.7 Application, Go to your project .env file and set up database credential and move next step.

Install Maatwebsite Package

We need to install Maatwebsite package, Open command prompt(CLI) and run the below command :

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,

],

After successfully Install & Configurtion Maatwesite Package, Use the below command and publish the package :

php artisan vendor:publish

This command will create a new config file named “config/excel.php”.

Add Fake Records

Now we need to add fake records in our datatabase, so we can simply import and export. First of run the migration command it will create some basics table in our database.

php artisan migrate

After that we need to run below command to add fake records in users table :

If you found any query builder error in command prompt go to  => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}
php artisan tinker 

>>>factory(App\User::class, 20)->create();

Create Controller

We need to create new controller. The controller manage all import export methods, open your terminal and run the below command.

php artisan make:controller TestController

This command will create our TestController, Go to app/Http/Controllers/TestController.php and put the below code here :

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Exports\ExportUsers;
use App\Imports\ImportUsers;
use Maatwebsite\Excel\Facades\Excel;
  
class TestController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function importExport()
    {
       return view('import');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function export() 
    {
        return Excel::download(new ExportUsers, 'users.xlsx');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function import() 
    {
        Excel::import(new ImportUsers, request()->file('file'));
           
        return back();
    }
}

Add Routes

Here, we will create routes for import export data to our database. Open your routes/web.php and create the below routes :

Route::get('import-export', 'TestController@importExport');
Route::post('import', 'TestController@import');
Route::get('export', 'TestController@export');

Create Import Class

Now we need to create a import class and use this class to our testController. Open the command Prompt and run the below command :

php artisan make:import ImportUsers --model=User

Go to the app/Imports/ImportUsers.php

<?php
  
namespace App\Imports;
  
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
  
class ImportUsers implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'name'     => $row[0],
            'email'    => $row[1], 
        ]);
    }
}

Create Export Class

Now we need to create a import class and use this class to our testController. Open the command Prompt and run the below command :

php artisan make:export ExportUsers --model=User

app/Exports/ExportUsers.php

<?php
  
namespace App\Exports;
  
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
  
class ExportUsers implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::get();
    }
}

Create Blade File

Next we will create import.blade.php. Go to app/resource/views and create import.blade.php, put the below code here :

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.7 Import Export Excel to database - Tuts Make</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
   
<div class="container">
    <div class="card mt-4">
        <div class="card-header">
            Laravel 5.7 Import Export Excel to database - Tuts Make
        </div>
        <div class="card-body">
            <form action="{{ url('import') }}" method="POST" name="importform" 
               enctype="multipart/form-data">
                {{ csrf_token() }}
                <input type="file" name="file" class="form-control">
                <br>
                <a class="btn btn-info" href="{{ url('export') }}"> 
                 Export File</a>
                <button class="btn btn-success">Import File</button>
            </form>
        </div>
    </div>
</div>
   
</body>
</html>

Start Development Server

In this step, we will use the php artisan serve command . It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/import-export

Or direct hit in your browser

http://localhost/ImportExportLaravel /public/import-export

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this article , We have successfully use the import export excel data to database using the maatwebsite package . our examples run quickly.

You may like

  1. Import Data From Excel & CSV to mysql Using Codeigniter
  2. Export Data to Excel/CSV in Codeigniter Using PHPExcel
  3. Laravel 6 Tutorial From Scratch | Step By Step
  4. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  5. Laravel 6 – Ajax CRUD (Operation) Application Example
  6. Laravel 6 Angular JS CRUD Example Tutorial
  7. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  8. Laravel 6 CKEditor with Image Upload
  9. Ajax Image Upload In Laravel Tutorial Example From Scratch
  10. Laravel 6 Intervention Upload Image Using Ajax – Example
  11. Laravel 6 Upload Image to Database with Validation

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

4 replies to Import Export Excel & Csv to Database in Laravel Example

  1. keep it up . easy example of import export in laravel 5.7

  2. Thank You so much it is very useful .

  3. If I want to import a row date?

Leave a Reply

Your email address will not be published. Required fields are marked *