• Contact Us
Wednesday, December 21, 2022
-18 °c
Teman Ngoding
  • Home
  • Tutorial
    • Laravel
    • Codeigniter
    • PHP
    • Golang
    • Java
    • Javascript
    • React JS
    • SQL
    • Problem Solution
  • Video Tutorial
    • Video Laravel
    • Video Codeigniter
    • C++
    • Video Git
  • Events
  • Berita
  • Donate
  • Indonesia
    • English
No Result
View All Result
Teman Ngoding
  • Home
  • Tutorial
    • Laravel
    • Codeigniter
    • PHP
    • Golang
    • Java
    • Javascript
    • React JS
    • SQL
    • Problem Solution
  • Video Tutorial
    • Video Laravel
    • Video Codeigniter
    • C++
    • Video Git
  • Events
  • Berita
  • Donate
  • Indonesia
    • English
No Result
View All Result
Plugin Install : Cart Icon need WooCommerce plugin to be installed.
Teman Ngoding
No Result
View All Result

Tutorial Import Export File Excel & CSV Laravel 9

admin by admin
April 11, 2022
in Laravel, Tutorial
0 0
0
Home Tutorial Laravel

This post is also available in: English

Impor ekspor excel atau CSV dari database adalah syarat utama untuk proyek admin. Dalam tutorial ini, saya akan menunjukkan cara mengimpor file CSV atau excel dan mengekspor file CSV atau excel menggunakan maatwebsite/excel di aplikasi laravel 9.

Laravel 9 Impor Ekspor File Excel & CSV ke Database Contoh

Sebaiknya, kita akan menggunakan plugin maatwebsite/excel composer untuk mengekspor dan mengimpor data, yang terpenting, untuk berinteraksi dengan database.

Saya akan berbagi pola kerja dengan Anda. Idealnya, bagaimana seharusnya Anda mengimpor-ekspor dan mengunduh file excel & CSV dari database menggunakan plugin maatwebsite/excel composer.

Laravel 9 Import Export Excel & CSV File Tutorial

Install Laravel

composer create-project laravel/laravel laravel-excel-csv --prefer-dist
cd laravel-excel-csv

Compose Database Connection

Tambahkan kode berikut di file .env.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Install Excel (maatwebsite) Pacakage

composer require maatwebsite/excel

Generate Fake Records, Migrate Table

php artisan migrate

Setelah migrasi selesai, jalankan perintah di bawah ini.

php artisan tinker
User::factory()->count(50)->create();
exit

Construct Route

Tentukan 3 route di route/web.php yang menangani impor dan ekspor untuk file Excel dan CSV.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('file-import-export', [UserController::class, 'fileImportExport']);
Route::post('file-import', [UserController::class, 'fileImport'])->name('file-import');
Route::get('file-export', [UserController::class, 'fileExport'])->name('file-export');

Buat Impor Class

php artisan make:import UsersImport --model=User

Tempatkan kode berikut di dalam file app/Imports/UsersImport.php.

<?php
namespace App\Imports;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UsersImport 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],
            'password' => Hash::make($row[2])
        ]);
    }
}

Construct Export Class

php artisan make:export UsersExport --model=User

Berikut adalah kode terakhir yang terkonjugasi di app/Exports/UsersExport.php.

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

Create and Prepare Controller

php artisan make:controller UserController

Tempatkan kode berikut di file app/Http/Controllers/UserController.php.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\UsersImport;
use App\Exports\UsersExport;
class UserController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function fileImportExport()
    {
       return view('file-import');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function fileImport(Request $request) 
    {
        Excel::import(new UsersImport, $request->file('file')->store('temp'));
        return back();
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function fileExport() 
    {
        return Excel::download(new UsersExport, 'users-collection.xlsx');
    }    
}

Buat Blade View

Buat file resources/views/file-import.blade.php untuk mengatur tampilan. Tempatkan kode berikut di dalam file tampilan blade:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Import Export Excel & CSV to Database in Laravel 7</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5 text-center">
        <h2 class="mb-4">
            Laravel 7 Import and Export CSV & Excel to Database Example
        </h2>
        <form action="{{ route('file-import') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group mb-4" style="max-width: 500px; margin: 0 auto;">
                <div class="custom-file text-left">
                    <input type="file" name="file" class="custom-file-input" id="customFile">
                    <label class="custom-file-label" for="customFile">Choose file</label>
                </div>
            </div>
            <button class="btn btn-primary">Import data</button>
            <a class="btn btn-success" href="{{ route('file-export') }}">Export data</a>
        </form>
    </div>
</body>
</html>

Setelah mengikuti setiap langkah, masing-masing, dan secara berurutan, sekarang saatnya menjalankan aplikasi untuk menguji apa yang kami bangun sejauh ini.

php artisan serve
http://localhost:8000/file-import-export
Tags: export laravelimport laravellaravellaravel 9laravel9
ShareTweetShare
admin

admin

Next Post
Datatable horizontal scroll

Datatable horizontal scroll

Leave a Reply Cancel reply

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

  • Trending
  • Comments
  • Latest
Tutorial CodeIgniter 4 part 1 ~ RESTful API JWT Authentication

Tutorial CodeIgniter 4 part 1 ~ RESTful API JWT Authentication

June 2, 2022
Codeigniter 4 ~ Membuat Notifikasi Menggunakan SweetAlert

Codeigniter 4 ~ Membuat Notifikasi Menggunakan SweetAlert

June 8, 2022
Tutorial Codeigniter 4 ~ Login dan Register

Tutorial Codeigniter 4 ~ Login dan Register

May 30, 2022
REST API Login dan Register Node.js dengan JWT

REST API Login dan Register Node.js dengan JWT

July 28, 2022
Tutorial Codeigniter 4 ~ Login dan Register

Tutorial Codeigniter 4 ~ Login dan Register

5
Rekomendasi tempat belajar pemrograman

Rekomendasi tempat belajar pemrograman

3
Menghilangkan Public dan Index.php dari URL Codeigniter 4

Menghilangkan Public dan Index.php dari URL Codeigniter 4

2
Membuat Sitemap Otomatis Codeigniter 4

Membuat Sitemap Otomatis Codeigniter 4

1
Access MongoDB With Node.JS

Akses MongoDB Dengan Node.JS

September 26, 2022
Teorema Structured Control

Basic Programming – Structured Control Theorem

September 23, 2022
WEB CRUD LocalStorage Menggunakan JavaScript

WEB CRUD LocalStorage Menggunakan JavaScript

September 22, 2022
DOM dan GOM Javascript

Perbedaan BOM Dan DOM Pada JavaScript

September 20, 2022
Teman Ngoding

Teman Ngoding tempat berbagi tutorial pemrograman
Read more

Categories

  • Berita
  • C++
  • Codeigniter
  • Events
  • Flutter
  • Golang
  • Java
  • Javascript
  • Laravel
  • MongoDB
  • News
  • Node JS
  • Pemrograman
  • PHP
  • Problem Solution
  • React JS
  • SQL
  • Tutorial
  • TypeScript
  • TypeScript
  • Video Codeigniter
  • Video Git
  • Video Laravel
  • Video Tutorial

Tags

ajax belajar golang belajar reactjs blog browser seluler Cara mendapatkan Uang dari Blog codeigniter codeigniter 3 codeigniter 4 codeigniter4 embed html Error Handling flutter flutter vs react native golang golang dasar html infinite scroll javascript javascript tutorial laravel laravel 8 laravel9 laravel 9 load more ajax Menggunakan Multiple select2 dan menyimpan dengan format json mongodb nodejs pdf pemrograman ajax pemrograman golang pemrograman php reactjs reactjs tutorial reactjs vs react native rest api rest api codeigniter 4 tutorial codeigniter 4 tutorial golang tutorial javascript tutorial laravel tutorial laravel 8 tutorial nodejs tutorial reactjs uang dari blog

Recent News

Access MongoDB With Node.JS

Akses MongoDB Dengan Node.JS

September 26, 2022
Teorema Structured Control

Basic Programming – Structured Control Theorem

September 23, 2022

© 2022 Teman Ngoding.

No Result
View All Result
  • Home
  • Tutorial
    • Laravel
    • Codeigniter
    • PHP
    • Golang
    • Java
    • Javascript
    • React JS
    • SQL
    • Problem Solution
  • Video Tutorial
    • Video Laravel
    • Video Codeigniter
    • C++
    • Video Git
  • Events
  • Berita
  • Donate
  • Indonesia
    • English

© 2022 Teman Ngoding.

Login to your account below

Forgotten Password?

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In
  • English
  • Indonesia