Berikut adalah tutorial lengkap untuk import file Excel ke database menggunakan Laravel 10. Dalam tutorial ini, kita akan menggunakan paket Maatwebsite Excel untuk mengimpor data Excel ke database.

Langkah 1: Instalasi Laravel dan Paket Maatwebsite Excel

1.1. Instalasi Laravel 10 (Jika belum memiliki proyek Laravel)

Jika belum memiliki proyek Laravel, buat proyek baru:

composer create-project --prefer-dist laravel/laravel blog
cd blog

1.2. Instalasi Package Maatwebsite Excel

Package ini memudahkan kita untuk mengimpor dan mengekspor file Excel. Instal dengan perintah berikut:

composer require maatwebsite/excel

1.3. Tambahkan Service Provider 

 Tambahkan baris berikut di file config/app.php pada bagian aliases:

'aliases' => Facade::defaultAliases()->merge([
        'Excel' => Maatwebsite\Excel\Facades\Excel::class,
])->toArray(),

Langkah 2: Buat Model dan Migration

2.1. Buat Model dan Migration

Kita akan membuat model Product dengan kolom name, description, dan price untuk menyimpan data dari Excel.

php artisan make:model Product -m

Edit file migration create_products_table.php di folder database/migrations:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Jalankan migration untuk membuat tabel products:

php artisan migrate

Saya asumsikan teman-teman sudah membuat database dan berhasil koneksi di laravel. Jika belum, silahkan ikuti tutorial sebelumnya di CRUD lengkap dengan fitur upload gambar di Laravel 10

Langkah 3: Buat File Import

3.1. Buat Kelas Import

Laravel memerlukan kelas khusus untuk menangani proses import data dari Excel. Kita akan membuat file ProductImport.php di folder App/Imports.

Gunakan perintah berikut untuk membuat import class:

php artisan make:import ProductsImport --model=Product

Edit file app/Imports/ProductsImport.php agar seperti ini:

<?php

namespace App\Imports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\ToModel;

class ProductsImport implements ToModel
{
    /**
     * Each row from the Excel file is passed to this method.
     * We will convert the row into a Product model instance.
     */
    public function model(array $row)
    {
        return new Product([
            'name' => $row[0],          // Kolom pertama di Excel
            'description' => $row[1],   // Kolom kedua di Excel
            'price' => $row[2],         // Kolom ketiga di Excel
        ]);
    }
}

kemudian buka model Product.php di folder Models dan edit menjadi sebagai berikut:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = ['name', 'description', 'price'];
}

Langkah 4: Buat Controller dan Route

4.1. Buat Controller untuk Import

Buat controller untuk menangani upload dan import file Excel:

php artisan make:controller ProductImportController

Edit file app/Http/Controllers/ProductImportController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ProductsImport;

class ProductImportController extends Controller
{
    /**
     * Show the form to upload and import Excel file.
     */
    public function showImportForm()
    {
        return view('import');
    }

    /**
     * Handle the Excel file upload and import it to the database.
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx',
        ]);

        // Menggunakan fasad Excel untuk mengimpor data
        Excel::import(new ProductsImport, $request->file('file'));
        return redirect()->back()->with('success', 'Data successfully imported.');
    }
}

4.2. Tambahkan Route

Tambahkan route untuk menampilkan form dan menangani proses import di file routes/web.php:

use App\Http\Controllers\ProductImportController;

Route::get('import', [ProductImportController::class, 'showImportForm'])->name('import.form');
Route::post('import', [ProductImportController::class, 'import'])->name('import');

Langkah 5: Buat View untuk Import Form

Buat file view bernama import.blade.php di folder resources/views:

resources/views/import.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Excel to Database</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h2 class="text-center">Import Products from Excel</h2>

    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label for="file">Choose Excel File</label>
            <input type="file" class="form-control" name="file" required>
        </div>
        <button type="submit" class="btn btn-primary">Import</button>
    </form>
</div>
</body>
</html>

Langkah 6: Test Import Excel

  1. Jalankan server Laravel:

    php artisan serve
  2. Buka browser dan akses form upload di http://localhost:8000/import.

  3. Upload file Excel dengan format seperti berikut:

    Product 1 Deskripsi produk 1 100.0
    Product 2 Deskripsi produk 2 200.0
     

    Pastikan file Excel memiliki urutan kolom sesuai dengan model yang telah kita buat (name, description, dan price).

Langkah 7: Hasil import

Jika step by step sudah dilakukan dengan benar, maka akan menghasilkan seperti berikut:

Setelah itu, check data di database apakah sudah berhasil import atau tidak. Jika berhasil, data akan bertambah di tabel products sebagai berikut:
Kesimpulan

Dengan mengikuti langkah-langkah di atas, Anda berhasil membuat fitur untuk import file Excel ke database di Laravel 10 menggunakan paket Maatwebsite Excel. Ini adalah cara yang efisien untuk menangani data dalam jumlah besar dari file Excel ke database.