How to import export csv and excel file in Laravel?

Today now in this post i will show you How to import export csv and excel file into database in Laravel? Here I am going to give you an example of how to import and export xls, xlsx and csv files from database in laravel. This example will also help you to implement on our Laravel application.

So now in this example through we can import the excel or csv to store in database and then export or download the excel or csv file from database table. For this example i will be use maatwebsite package from the scratch.

All Step In Bellow:

By using Maatwebsite package we can easily working on csv and excel file. We know maatwebsite packages is also provide to easily get data, also we can group by data, also create the more then one sheet etc.

Step 1: Install Laravel Application

Now In this step, if we haven’t laravel application setup then we need to get the fresh laravel application. So run the bellow command and get clean and fresh laravel application.

composer create-project --prefer-dist laravel/laravel new_project
Step 2: Install Package

Now in this step we need to add the maatwebsite package so open your cmd or terminal and then fire the bellow command:

composer require maatwebsite/excel

Then After successfully install the package, need open config/app.php file and then add service provider and alias.

config/app.php
'providers' => [
	....
	Maatwebsite\Excel\ExcelServiceProvider::class,
],

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

],
Step 3: Create Item Table and Model

At first need to create “item” model for items, so we can create file by using bellow command:

php artisan make:model Item -m
app/Model/Item.php

you have to put bellow code on this file app/Model/Item.php .

namespace App;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
   public $fillable = ['title','description'];
}

After this command you will also find one file in the following path database/migrations and you need to put the bellow code in our migration file for create items table.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->text('description');
           $table->timestamps();
       });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("items");
    }
}
Step 4: Create Route

Now in this is step we have to create the route of import export file. so need open our routes/web.php file and add the following route.

routes/web.php
Route::get('importExport', 'MaatwebsiteDemoController@importExport');
Route::get('downloadExcel/{type}', 'MaatwebsiteDemoController@downloadExcel');
Route::post('importExcel', 'MaatwebsiteDemoController@importExcel');
Step 5: Create Controller

Now in this part, now we need to create the new controller as MaatwebsiteDemoController in this path app/Http/Controllers/MaatwebsiteDemoController.php. Now this controller will manage all the impostExport, downloadExcel and importExcel request and also return response, so put the bellow content in controller file:

app/Http/Controllers/MaatwebsiteDemoController.php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Model\Item;
use Excel;


class MaatwebsiteDemoController extends Controller
{


	/**
     * Return View file
     *
     * @var array
     */
	public function importExport()
	{
		return view('importExport');
	}


	/**
     * File Export Code
     *
     * @var array
     */
	public function downloadExcel(Request $request, $type)
	{
		$data = Item::get()->toArray();
		return Excel::create('itsolutionstuff_example', function($excel) use ($data) {
			$excel->sheet('mySheet', function($sheet) use ($data)
	        {
				$sheet->fromArray($data);
	        });
		})->download($type);
	}


	/**
     * Import file into database Code
     *
     * @var array
     */
	public function importExcel(Request $request)
	{

		if($request->hasFile('import_file')){
			$path = $request->file('import_file')->getRealPath();
			$data = Excel::load($path, function($reader) {})->get();
			if(!empty($data) && $data->count())
                 {
				foreach ($data->toArray() as $key => $value) {
					if(!empty($value)){
						foreach ($value as $v) {		
							$insert[] = ['title' => $v['title'], 'description' => $v['description']];
						}
					}
				}		
				if(!empty($insert)){
					Item::insert($insert);
					return back()->with('success','Insert Record successfully.');
				}
			}
		}
		return back()->with('error','Please Check your file, Something is wrong there.');
	}


}

Step 6: Create View

Now this last step, let’s create the ImportExportNew.blade.php(resources/views/importExportNew.blade.php) for layout and we need to write design code here and put the following code:

resources/views/importExportNew.blade.php
<html lang="en">
<head>
	<title>Import - Export Laravel </title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>


<body>
<br/>
<br/>
	<div class="container">		
		<div class="panel panel-primary">
		  <div class="panel-heading">
		    <h3 class="panel-title" style="padding:12px 0px;font-size:25px;"><strong>Laravel 5.3 - import export csv or excel file into database example</strong></h3>
		  </div>
		  <div class="panel-body">


		  		@if ($message = Session::get('success'))
					<div class="alert alert-success" role="alert">
						{{ Session::get('success') }}
					</div>
				@endif


				@if ($message = Session::get('error'))
					<div class="alert alert-danger" role="alert">
						{{ Session::get('error') }}
					</div>
				@endif


				<h3>Import File Form:</h3>
				<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">


					<input type="file" name="import_file" />
					{{ csrf_field() }}
					<br/>


					<button class="btn btn-primary">Import CSV or Excel File</button>


				</form>
				<br/>

		    	
		    	<h3>Import File From Database:</h3>
		    	<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;"> 		
			    	<a href="{{ url('downloadExcel/xls') }}"><button class="btn btn-success btn-lg">Download Excel xls</button></a>
					<a href="{{ url('downloadExcel/xlsx') }}"><button class="btn btn-success btn-lg">Download Excel xlsx</button></a>
					<a href="{{ url('downloadExcel/csv') }}"><button class="btn btn-success btn-lg">Download CSV</button></a>
		    	</div>


		  </div>
		</div>
	</div>


</body>


</html>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.