Current Location: Home> Latest Articles> Complete Guide to Exporting Database Tables and Creating Seeds in Laravel

Complete Guide to Exporting Database Tables and Creating Seeds in Laravel

gitbox 2025-08-10

Background

Laravel is a popular PHP framework that offers a variety of tools to simplify development tasks. In daily development, it’s common to export table data from the database and create seed files (Seeders) to quickly restore or initialize data in different environments. This guide will walk you through how to efficiently implement this process using Laravel.

Exporting Database Table Data

Laravel provides several ways to export database table data, with the most common being Artisan commands and Eloquent models.

Exporting with Artisan Command

The Artisan command-line tool included with Laravel is very powerful, allowing you to export data with simple commands. For example:

php artisan export --table=users --output=users.csv

This command exports the users table data into a users.csv file.

Exporting with Eloquent Model

In addition to using the command line, you can export data more flexibly with Eloquent models. First, create a model:

php artisan make:model User

Then, in your controller, retrieve the data and save it as a CSV file:

$users = User::all();
$csvData = '';
foreach ($users as $user) {
    $csvData .= $user->name . ',' . $user->email . "\n";
}
file_put_contents('users.csv', $csvData);

This will export all user information to a users.csv file.

Creating Seed Files

Seed files (Seeders) are used to populate the database with bulk data. Laravel offers a simple way to generate them.

Generating a Seeder with Artisan

Run the following command to create a seeder file named UsersTableSeeder:

php artisan make:seeder UsersTableSeeder

In the generated Seeder file, add the data seeding logic, for example:

use App\Models\User;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        factory(User::class, 10)->create();
    }
}

The above code uses a factory to create 10 user records.

Running the Seeder

To insert the data into the database, execute the following command:

php artisan db:seed

This will run all registered Seeder files and populate the corresponding tables with data.

Conclusion

By leveraging Laravel’s Artisan commands and Eloquent models, you can efficiently export table data and create Seeder files, making database migration and initialization much easier. These tools significantly boost productivity during both development and deployment.