Laravel 10 Create Seeder for Database Seeding Tutorial

Reading Time: 6 minutes
557 Views

In web application development, populating your database with initial data is a regular process, especially during the testing and development phases. Through database seeding, Laravel 10, a strong PHP framework, streamlines this process.

In Laravel 10, seeders are a powerful tool that can be used to populate your database with test data. A seeder is essentially a class that defines the data to be inserted into the database, and Laravel provides an easy-to-use Seeder class that can be extended to create your own seeders.

In this tutorial, we will walk you through the process of constructing a seeder for database seeding in Laravel 10, allowing you to generate and insert sample data into your application’s database tables easily.

Read More: Laravel 10 Mailable Email Template Components 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

How To Create Migration in Laravel?

Here, you will create a events table using migration and then seed test data inside it.

Open project into terminal and run this command to create a migration file,

php artisan make:migration create_events_table

It will create xxx_create_events_table.php file inside /database/migrations folder. Open migration file and write this following code into it.

The code is for the schema of events table.

<?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(): void
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->string('title', 50);
            $table->date('start');
            $table->date('end');
            $table->timestamps();
        });
    }

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

Run Migration

Back to terminal and run this command.

php artisan migrate

It will create events table inside database.

Read More: How To Create a Custom 404 Page in Laravel 10 Tutorial

Next,

How To Create Data Seeder in Laravel?

Copy this command and run into terminal to create a data seeder for events table.

php artisan make:seeder FakeEventSeeder

It will create a file FakeEventSeeder.php inside /database/seeders folder.

Open file and write this following code into it,

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Event;

class FakeEventSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run(): void
    {
        $data = [
            ['title' => 'Fake Event-1', 'start' => '2023-03-11', 'end' => '2023-03-12'],
            ['title' => 'Fake Event-2', 'start' => '2023-03-15', 'end' => '2023-03-17'],
            ['title' => 'Fake Event-3', 'start' => '2023-03-25', 'end' => '2023-03-27'],
            ['title' => 'Fake Event-4', 'start' => '2023-03-20', 'end' => '2023-03-23'],
        ];
      
        foreach ($data as $key => $value) {
          
            Event::create($value);
        }
    }
}

How To Run Laravel Data Seeder?

You have multiple options available to execute a seeder class file to database. Here, you will get the concept of about these two –

  • Using DatabaseSeeder
  • Without Using DatabaseSeeder

Method#1: Using DatabaseSeeder

You need to load your seeder class (FakeEventSeeder.php) into DatabaseSeeder.php which should be inside /database/seeders folder.

Open file and load into it,

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Database\Seeders\FakeEventSeeder;

class DatabaseSeeder extends Seeder
{
     /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->call(FakeEventSeeder::class); // Run Seeder Class
    }
}

Run Seeder

Back to terminal and run this command.

php artisan db:seed


Method#2: Without Using DatabaseSeeder

Here, you have to run FakeEventSeeder.php file directly instead of loading anywhere.

Artisan command to call any specific seeder file,

php artisan db:seed --class=FakeEventSeeder

Read More: Laravel 10 Eloquent Has One Through Relationship Tutorial

You have to add class flag with seeder class name. It runs specified seeder class name.

Database seeding with Laravel 10 seeder

That’s it.

We hope this article helped you to learn about How To Use Laravel 10 Seeder for Database Seeding Tutorial in a very detailed way.

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