Laravel 10 Export MySQL Table Data into CSV File Tutorial

Reading Time: 6 minutes
551 Views

Inside this article we will see the concept of Laravel 10 Export MySQL Table Data into CSV File Tutorial. Article contains classified information about How To export data in CSV format in laravel application.

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

Read More: How To Upload File Using Livewire in Laravel 10 Tutorial

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

Read More: Laravel 10 Working with Eloquent Mutators and Accessors

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 2023_03_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;
}

Next,

Create Data Factory

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.

Read More: How To Crop Image Before Upload in Laravel 10 Using Croppie.js

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

Run this command into project terminal 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 10 Export MySQL Table Data into CSV File Tutorial in a very detailed way.

Read More: Laravel 10 How To Create Signature Pad Using jQuery

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more