Skip to main content

How to Import and Export CSV or Excel file into Laravel 5.8 | maatwebsite/excel | JayviTech

In this post we learn how to import and export CSV or Excel file using maatwebsite/excel version 3 in laravel 5.8 project.
In this tutorial we will import a data to csv, xls file and import this excel data into database.
Excel Import Export Image
Import and Export Excel/CSV file demo
A package maatwebsite/excel provide easy way to import and export CSV. we use latest version of maatwebsite/excel version 3.
So, let's start:
Step 1: Install Laravel 5.8 Project
Type the following command.
 composer create-project --prefer-dist laravel/laravel blog "5.8.*" 
Step 2: Install Maatwebsite Package
Type the following command to install maatwebsite/excel package.
 composer require "maatwebsite/excel" 
Then open config/app.php file and add service provider and aliase name.
'providers' => [
....
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
....
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
Then after publish your package by following command
 php artisan vendor:publish 
Step 3: Generate A Dummy Records
In this step, we have to require "users" table with some dummy records, so we can simply import and export. So first you have to run default migration that provided by laravel using following command:
 php artisan migrate 
After that we need to run following command to generate dummy users:
 php artisan tinker 
Then write in terminal
factory(App\User::class, 20)->create();

Step 4: Define the route name under the web.php file
Route::get('export''ExcelController@exportData')->name('export_data'); Route::get('display-view''ExcelController@displayView'); Route::post('import''ExcelController@importData')->name('import_data');

Step 5: Create a Import Class
In maatwebsite 3 new version provide built import class and we have to use in controller. So we create new Import class. you have to run following command:
 php artisan make:import UsersImport --model=User 
Open app/Imports/UsersImport.php file and do following code.
<?php namespace App\Imports; use App\User; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; class UsersImport implements ToModelWithHeadingRow {     /**     * @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 6: Create a Export Class
maatwebsite 3 new version provide built export class and we have to use in controller. So we can create new Export class. you have to run following command:
 php artisan make:export UsersExport --model=User 
Open app/Imports/UsersExport.php file and do following code.
<?php namespace App\Exports; use App\User; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; class UsersExport implements FromCollectionWithHeadings {     /**     * @return \Illuminate\Support\Collection     */     public function collection() {         return User::all();     }     public function headings(): array {         return [             'Id',             'Name',             'Email',             'Email Verified At',             'Remember Token',             'Created Date',             'Updated Date',         ];     } }

Step 7: Create a ExcelController
We create new controller name ExcelController by using php artisan make:controller ExcelController.
This controller handle all route action. So, put bellow code into app/Http/Controllers/ExcelController.php file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Exports\UsersExport; use App\Imports\UsersImport; use Maatwebsite\Excel\Facades\Excel; class ExcelController extends Controller {     public function displayView(){        return view('import_csv');     }     public function exportData() {         return Excel::download(new UsersExport'users.xlsx');     }     public function importData() {         Excel::import(new UsersImport,request()->file('file'));         return back();     } }

Step 8: Create a import_csv.blade.php
Last step is to create a import_csv.blade.php under the (resources/views/import_csv.blade.php) folder. we create a layout and design code into this file so write below code:
<!DOCTYPE html> <html>     <head>         <title>Laravel 5.8 Import and Export CSV or Excel file by www.jayvitech.blogspot.com </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">                 <div class="card-header">                     Laravel 5.8 Import and Export CSV or Excel file by www.jayvitech.blogspot.com                 </div>                 <div class="card-body">                     <form action="{{ route('import_data'}}" method="POST" enctype="multipart/form-data">                         @csrf                         <input type="file" name="file" class="form-control">                         <br>                         <button class="btn btn-success">Import User Data</button>                         <a class="btn btn-info" href="{{ route('export_data'}}">Export User Data</a>                     </form>                 </div>             </div>         </div>     </body> </html>

Step 9: Run Project
Finally we run project by following command:
 php artisan serve 
Make a following example file in Excel and save sample.csv file.

Excel Image
Excel Import File example

See also Image Compress demo in laravel 5.8
Conclusion
Using the maatwebsite/excel version 3 we import and export a CSV/Excel file into Laravel 5.8 Project. I hope this example help you for import/export CSV file into laravel.
So, Guys please Share PHP Artisan with Jay Chauhan Blog to your Technical friends and do the best coding with an easy way.
🙏🙏🙏💃💓

Comments

  1. Nice tutorials for import and export excel in laravel.
    keep posting jay

    ReplyDelete
  2. I appreciate this piece of useful information. We are provide Export Import Course Online and Certificate Training to Understand How To Start Export Business For more information visit our site: Export Import Course Online

    ReplyDelete

Post a Comment

Show Latest Post

Laravel 5.8 Digital Signature - Signature Pad | Jquery signature pad | JayviTech

In this post we can learn how to make Digital  Signature Pad  into your Laravel 5.8 project. Using the JavaScript Library we can draw the smooth signatures, It is a HTML5 Canvas based. It is working for all modern browsers, desktop and mobile browsers. Signature Pad Watch  What is MVC Structure? Watch to learn:  Laravel 7 Tutorial We create a Digital E-Signature Pad with saving as a image using HTML5 canvas. So, Let's start: Step 1: Install Laravel 5.8 Project Type the following command. composer create-project --prefer-dist laravel/laravel blog "5.8.*" Step 2: Define the route name under the web.php file Route :: get ( '/signature-pad' ,  function  () {      return   view ( 'signature-pad' ); }); Step 3: Create a Signature Pad Now we can create a Signature Pad view, then after we can watch how our signature pad look like into our Laravel project. Create a  signature-pad.blade....

Add and Remove Input Fields Dynamically with Jquery Laravel 5.8 | PHP | JayVitech

In this post we will learn how to "Add and Remove Input Fields Dynamically with Jquery Laravel 5.8". Today, we add and remove input fields dynamically using jquery and save to the database in laravel 5.8 Project. Dynamically add input fields are usefull when you add or clone same input fields to enter the different data into form. It is good option when you need to get multiple values of same field. So, let's start: Watch Now Laravel 7 new Feature - Components Step 1: Install Laravel 5.8 Project Type the following command: composer create-project --prefer-dist laravel/laravel dynamic-fields "5.8.*" Step 2: Database Configuration In this step we configure the database. We put the database details like database name, username and password to store the data. open .env file into laravel project folder. DB_CONNECTION =mysql DB_HOST = 127.0.0.1 DB_PORT = 3306 DB_DATABASE =jayvitech (Your database name) DB_USERNAME =root (Your user name) DB_PASS...

Image Compress demo in laravel 5.8 | Intervention Image - Resize image | JayviTech

In this post we will learn "How to compress image before upload in laravel 5.8" . We use intervention in laravel for compress a image. using a Laravel intervention we can easily compress a any type of image format. Intervention image package allows a image to compress and resize in laravel project. So, let's start: Step 1: Install Laravel 5.8 Project Type the following command. composer create-project --prefer-dist laravel/laravel blog "5.8.*" Step 2:  Install Intervention Image We will install intervention/image package for resize image. Using this package we can make thumbnail image. Type the following command: composer require intervention/image Then open  config/app.php  file and add service provider and aliase name. 'providers' => [ .... Intervention\Image\ImageServiceProvider::class, ], 'aliases' => [ .... 'Image' => Intervention\Image\Facades\Image::class, ], Then after publi...