• Hello, Visitor
  • Thursday, June 12, 2025
Search Result
Home » Laravel » Laravel Add Data to Database with Database Seeder

Laravel Add Data to Database with Database Seeder

Hello friends, today in this blog you’ll learn how to add data to the database on laravel with database seeder.

Laravel Seeder: Laravel offers a tool to include dummy data in the database automatically. This process is called seeding. Developers can add simply testing data to their database table using the database seeder. It is extremely useful as testing with various data types allows developers to detect bugs and optimize performance.

Now, let's see how we can add data to the database on laravel with database seeder.

You can also check our video tutorial about how to add data to the database on laravel with database seeder



Step 01: Make model and migration

Open the terminal and run this command to make Post model and migration

php artisan make:model Post -m


now go to database/migrations directory and open create_posts_table_migration.php file and paste this code inside up() function

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title')->nullable();
    $table->longText('content')->nullable();
    $table->string('status')->default(1);
    $table->timestamps();
});


now go to app/models directory and open Post.php file and add this code inside the class function

use HasFactory;
protected $table = 'posts';


now, migrate the migration with this command

php artisan migrate


Step 02: Make seeder

Open the terminal and run this command to make Post table seeder

php artisan make:seeder PostTableSeeder


now, go to database/seeder directory and open PostTableSeeder.php file, and use these codes inside the run() function

DB::table('posts')->insert([
    'title' => $faker->sentence(5),
    'content' => $faker->paragraph(4),
]);


now, go to database/seeder directory and open DatabaseSeeder.php file, and use these codes inside the run() function

$this->call([
    PostTableSeeder::class,
]);


now, open the terminal and run this command to run the seeder

php artisan db:seed


now, check the database table and you can get your data added to the post table.

That's it for this post. Hope it will help you.


Leave a Reply

You must Login to add a comment