100% Import data by using csv or excel file in laravel

100% Import data by using csv or excel file in laravel

100% Import data by using csv or excel file in laravel

1st Step: Package install 

Install maatwebsite package for import data by using laravel 5.8. First you need to install a maatwebsite package for excel or csv file import. Use blew command:

composer require maatwebsite/excel

Now in In your project folder open config/app.php file and connect Maatwebsite providesr and aliases class.

config/app.php

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

2nd Step: Importer create

Now you need create a importer by using blew artisan command. By this command it will create a file in app/importer folder where under this we to define table column which data we want to get from CSV file. 


php artisan make:import CsvImport --model=Institute

App/Imports/CsvImport.php


<?php
namespace App\Imports;
use App\Institute;
use Maatwebsite\Excel\Concerns\ToModel;
class CsvImport implements ToModel
{
    public function model(array $row)
    {
        return new Institute([
            'InstituteName'=>$row[0],
            'InstituteCategory'=>$row[1],
            'EducationLevel'=>$row[2],
            'MobileNo'=>$row[3],
            'InstituteEmail'=>$row[4],
            'Division'=>$row[5],
            'District'=>$row[6],
            'Upazila'=>$row[7],
            'PostOffice'=>$row[8],
            'InstituteAddress'=>$row[9],
        ]);
    }
}

3rd step: controller create

php artisan make:controller CsvFile


<?php
namespace App\Http\Controllers;
use App\Imports\CsvImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Institute;
class CsvFile extends Controller
{
    public function csv_import(){
        Excel::import(new CsvImport,request()->file('file'));
        return back();
    }
}


4th step: create route

Route::post('csv_file/import', 'CsvFile@csv_import')->name('import');


5th step: file import view


<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" accept=".csv">
<br>
<button class="btn btn-success">Import User Data</button>
{{--<a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>--}}
</form>

Now run your project and upload file.

====Done ===

Related Jobs

Comments


  • import data by csv
  • laravel import
  • maatwebsite import package
  • laravel file import system