Laravel 9 Export MySQL Table Data into CSV File Tutorial

Share this Article
Reading Time: 6 minutes
2,489 Views

Inside this article we will see the concept of Laravel 9 Export MySQL Table Data into CSV File format. Article contains the classified information about this topic. You will get the whole idea to dump your database data into CSV file.

If we have an application which basically built for reporting then we need some kind of function which export tabular data into CSV format.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

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

Create Migration

We will create a products table using migration and then we seed test data inside it.

Open project into terminal and run this command.

$ php artisan make:migration create_products_table

It will create 2022_04_17_031027_create_products_table.php file inside /database/migrations folder.

Open xxx_create_products_table.php and write this code into it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name", 70);
            $table->string("slug", 100);
            $table->text("description");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create products table inside database.

Create Model

Back to project terminal and run these command to create model.

$ php artisan make:model Product

It will create Product.php file inside /app/Models folder. This file will help when we generate data using factory and insert into table.

Open Product.php and write this code into it.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    public $timestamps = false;
}

Create Data Factory

Next,

Copy this command and run into terminal to create a factory file.

$ php artisan make:factory ProductFactory

It will create a file ProductFactory.php inside /database/factories folder.

Open ProductFactory.php file and write this following code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'description' => $this->faker->text,
        ];
    }
}

Call Model Factory

Open DatabaseSeeder.php from /database/seeders folder. Load model and factory.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
         \App\Models\Product::factory(100)->create();
    }
}

Concept

\App\Models\Product::factory(100)->create();

It will generate 100 fake rows for products table.

Run Data Seeder

Back to project terminal and run this command to run factory to seed fake data.

$ php artisan db:seed

It will generate and save fake data into products table.

Table: products

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller DataController

It will create DataController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class DataController extends Controller
{
    public function downloadCSVReport()
    {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=product-' . date("Y-m-d-h-i-s") . '.csv');
        $output = fopen('php://output', 'w');
      
        fputcsv($output, array('Id', 'Name', 'Slug'));

        $products = Product::get();

        if (count($products) > 0) {

            foreach ($products as $product) {

                $product_row = [
                    $product['id'],
                    ucfirst($product['name']),
                    $product['slug']
                ];

                fputcsv($output, $product_row);
            }
        }
    }
}

Add Route

Open web.php file from /routes folder. Add this route into it.

//...

use App\Http\Controllers\DataController;

// Route to download product CSV
Route::get("download-csv", [DataController::class, "downloadCSVReport"]);

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL – http://127.0.0.1:8000/download-csv

When you hit above URL, it will download a CSV file with name product-{datetime}.csv

We hope this article helped you to learn about Concept of Laravel 9 Export MySQL Table Data into CSV File Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5