Insert data using Database Seeder in Laravel

In this tutorial you will learn about the Insert data using Database Seeder in Laravel and its application with practical example.

Insert data using Database Seeder in Laravel

There are many instances where we need a populated database with test data in order to test the working of various operation. Populating Test data manually is time consuming, but Laravel provides a simple method of seeding test data in your database automatically instead doing it manually. In laravel you are required to created seeder classed per table, all these classes are stored in the database/seeds directory.

Today in this article, we will learn how to insert data using Database Seeder in Laravel. I’ll show you how to create database seeder class for a table, seed data in seeder, call database seeder and run database seeder. In this example, we assume that we already have admins table created and wants to seed some test data into it.

Create Seeder Using Artisan Command

Seeder class file can be generated using following artisan command:

Syntax:-

Example:-

Once the above command is executed, this will generate a seeder class file in the database/seeds directory. This class has a default run() method.

database/seeds/AdminsTableSeeder.php

Add Data In Seeder Class file

Lets open seeder class file and within default run() method, we can populate single or multiple records as following:

Add Single Record:-

Add Multiple Records:-

Call Seeder

Laravel comes with a default seeder class named DatabaseSeeder which is executed by default when the db:seed command invoked. This class can be used to call user-defined seeders like this:

Run Seeder

Once the seeder classes are setup, we are ready to run laravel seeders using following artisan command:

We can also run a specific seeder class directly without adding it to the DatabaseSeeder class as following:

Call Seeder from Route

Call Seeder from Controller

Call Seeder from Migration

In this tutorial we have learn about the Insert data using Database Seeder in Laravel and its application with practical example. I hope you will like this tutorial.