Import Export CSV/EXCEL File In Laravel

In this post we will see import export csv excel file in laravel. We will simple create import data to csv, xls file and also we can import data to database using csv file in laravel 7 application.

Using this example we can easily import and export csv file in laravel and download the excel & CSV file from the database using the maatwebsite/excel composer package. maatwebsite/excel provide easy way to import and export using database model.So let's Start

 Step 1: Create new project for import and export csv file in laravel

We are creating new project setup for import and export csv file in laravel and import and export excel in laravel.

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

 

 

 Step 2: Database Setup

In this step, we will configure database. So open .env file and fill all details like as bellow: 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database name(import_export_demo)
DB_USERNAME=database username(root)
DB_PASSWORD=database password(NULL)

 

Step 3: Install Package

Now, we are going to install the Maatwebsite package using the below command.

composer require maatwebsite/excel

After that you need to add providers and alias in your project's config/app.php file

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

 

 Step 4: Create Some Dummy Records Using Tinker

After adding aliases and providers are adding some dummy records in databse using below command.

php artisan tinker

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

 

 Step 5: Create New Route

Now in this step we are creating new route for this example in this path routes/web.php

Route::get('import_export', 'Import_Export_Controller@importExport');
Route::post('import', 'Import_Export_Controller@import');
Route::get('export', 'Import_Export_Controller@export');

 

 

Step 6: Add Controller

Create the Import_Export_Controller using the following command.

php artisan make:controller Import_Export_Controller

After run this command we need to add below code in this controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\ExportUsers;
use App\Imports\ImportUsers;
use Maatwebsite\Excel\Facades\Excel;

class Import_Export_Controller extends Controller
{
     public function importExport()
    {
       return view('import');
    }

    public function export() 
    {
        return Excel::download(new ExportUsers, 'users.xlsx');
    }

    public function import() 
    {
        Excel::import(new ImportUsers, request()->file('file'));
            
        return back();
    }
}

 

Step 7: Create Import Class

Now, we will create the import class using the below command.

php artisan make:import ImportUsers --model=User

After run this command you will find ImportUsers.php in this path app\Imports\ImportUsers.php add below code in this file.

<?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],
        ]);
    }
}

 

Step 8: Create Export Class

Now, we will create the export class using the below command.

php artisan make:export ExportUsers --model=User

After run this command you will find ExportUsers.php in this path app\Export\ExportUsers.php add below code in this file.

<?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::all();
    }
}

 

Step 9: Create Blade File for View

Now create import.blade.php file for view in this path resources/views/import.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Import Export CSV/EXCEL File In Laravel - techsolutionstuff</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<h3>Import Export CSV/EXCEL File In Laravel - techsolutionstuff.com</h3>
	<form action="{{ url('import') }}" method="POST" name="importform"
	  enctype="multipart/form-data">
		@csrf
		<div class="form-group">
			<label for="file">File:</label>
			<input id="file" type="file" name="file" class="form-control">
		</div>
		<div class="form-group">
			<a class="btn btn-info" href="{{ url('export') }}">Export File</a>
		</div> 
		<button class="btn btn-success">Import File</button>
	</form>
</div>
</body>
</html>

 Now , We all completed with our code So, it's time to run this project..

 

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS