Database seeding is the process of seeding a database with actual or dummy data, according to Wikipedia. Seeding a database is the process of providing an initial collection of data to a database after setup. It's especially beneficial when we need to populate the database with data that we'll need later.
Database Seeding is required when we went to add testing data into our application which looks exactly entered by a user. Testing is another major use of database seeding in Laravel.
Suppose one of our application's functionality is searching, so whenever the user enters a query it will show a few results ranked from thousands of data from our database. In searching applications, response time plays a major role. So for testing response time to search thousands of records we need to add those records to our database. Manually adding those data can be time taking and stressful but with database seeding, it becomes easier. In addition, we can control data duplicity and data type validation.
Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. The database\seeders\DatabseSeeder.php helps us to manage order of database seeding into Laravel
Let's take example for database Seeding.
Laravel is MVC Framework and Model is fundamentally base class for application logic. In Laravel application, Model communicate with database and responsible for each data.
Let's make model with migration for posts with below command.
php artisan make:model Post -m
Here, we are planning for mass assignment so we need to add our fields into fillable array.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'date',
'name'
];
}
Open database/migrations/timestamp_posts_table.php file and let's define database structure for posts table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->date('date');
$table->string('user');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
Here, we have defined database table structure just to save post title, description, date, user and timestamps. In actual model you can add any numbers of field as per your requirement.
To run migration execute the given below command into terminal:
php artisan migrate
It will generate database table by name posts.
Here, we will creating seeder with dummy data so we will use factory and faker methods to seed data. Factory is very useful while testing for creating multiple data at a time. Factories return default set of data by defined datatype.
To create factory hit below command into terminal :
php artisan make:factory PostFactory
With this command you will get new file database\factories\PostFactory.php file. Let's modify it as per our requirements.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PostFactory extends Factory
{
public function definition()
{
return [
'title' => $this->faker->sentence(),
'description' => $this->faker->text(),
'date' => $this->faker->date(),
'user' => $this->faker->sentence(),
];
}
}
the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing. Here, we have used some faker methods to get appropriate data.
In this step, we will create seeder for post model and configure factory to create specific number of records to database. Enter below command to create Seeder :
php artisan make:seeder PostSeeder
The above command will create database/seeders/PostSeeder.php file into your application. Let's make some changes to call model factory for creating 100 posts.
<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
public function run()
{
Post::factory()
->count(100)
->create();
}
}
While using multiple seeder into our application, sometimes we need to set hierarchy. With DatabaseSeeder you can set which seeder will execute first and in which order.
With Database Seeder you don't need to seed each and every class individually. You can configure all seeders into database seeder and it will execute.
database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
PostSeeder::class,
]);
}
}
Finally, We have created our seeder and it's time to seed our database. Enter below command into terminal :
php artisan db:seed
It will seed all your seeders defined in your DatabaseSeeder.
You can seed also seed single seeder using below command
php artisan db:seed --class=PostSeeder
In some cases, you need to create fresh database with seeding then you can use below command :
php artisan migrate:fresh --seed
Sometimes after creating a new seeder you face an error, so you might require to regenerate Composer’s auto loader.:
composer dump-autoload
Here we have taken example for post table and seed data into it. In actual product, you need to seed fixed data to our application when you can use Laravel's database seeding functionality and seed those data with simple commands.
In this example, we used faker for generating data but you can use CSV, JSON files, excel file, XML data, Arrays or any other format of data using Seeders. You just need to alter reading logic for those data.
Ask anything about this examples