DEV Community

Dhiecoderweb
Dhiecoderweb

Posted on Originally published at dhiecoderweb.com

How to Import Excel Data into a Laravel Database

Importing data from an Excel file into a database is a very common need in business applications — from importing product data and employee data to transaction data. Laravel doesn't have this feature built in, but there is a popular package called Laravel Excel (by Maatwebsite) that is very easy to use and feature-rich. This tutorial will guide you from installation to importing with data validation.

Installing Laravel Excel

Install the package using Composer:

composer require maatwebsite/excel
Enter fullscreen mode Exit fullscreen mode

For Laravel 11, the service provider and facade are registered automatically. For Laravel 10 and below, publish the optional configuration:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Enter fullscreen mode Exit fullscreen mode

Make sure the following PHP extensions are enabled (they usually are by default):

  • php_zip
  • php_xml
  • php_gd2

Preparing the Model and Migration

Example use case: importing product data from Excel.

php artisan make:model Product -m
Enter fullscreen mode Exit fullscreen mode
// Migration
public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('sku')->unique();
        $table->string('name');
        $table->string('category')->nullable();
        $table->decimal('price', 12, 2);
        $table->integer('stock')->default(0);
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:

How to Import Excel Data into a Laravel Database

More programming tutorials and developer tools are also available at dhiecoderweb.com.

Top comments (0)