Dummy data in laravel
by durlavk
Recently found out about using seeder to create fake data in laravel. Infact it can be used with factory π§βπ.
Dummy or fake data generation is an important part of testing database or visualizing data in browser. Laravel being a popular framework has a few ways to create dummy data. Now you can manually fill the database for testing but filling up data after every fresh migration is just too slow and you can do better than that. Letβs discuss two ways you might want to create dummy data.
- Factory -
This is probably the more famous and used one. Factory uses
faker
library to generate data. In order to create fake data we have to create a factory of the same model name. To create a factory for aPost
model, we have to create aPostFactory
by the commandphp artisan make:factory PostFactory
. InPostFactory.php
changedefinition()
method as -public function definition() { return [ 'title' => $this->faker->sentence(), 'body' => $this->faker->paragraph(), ]; }
The faker library will provide us with fake value of sentence and paragraph. In order create the fake data now we just have to open tinker with
php artisan tinker
and run in tinker consolePost::factory()->create()
. - Seeding -
This is something I found recently. Creating dummy data by seeding is as easy as it gets. To create a seeder for
Post
model runphp artisan make:seeder PostSeeder
. InPostSeeder
changerun
method as-public function run() { Post::create([ 'title' => 'lorem ipsum dolor imit', 'body' => 'Similique molestias exercitationem officia aut. Itaque doloribus et rerum voluptate iure. Unde veniam magni dignissimos expedita eius.', ]); }
In a seeder we provide value for all the required fields. And although it seems like just adding everything yourself, it has some nice advantages which you will see. Also if you already have a factory setup like we do, you can simply use the factory rather than adding all the field data.
public function run() { Post::factory()->create(); }
Now add the
PostSeeder
todatabase/seeders/DatabaseSeeder.php
run
method$this->call([PostSeeder::class])
. In order to store the data in database runphp artisan db:seed
. Your seed data is thus stored in database. To view it you can runPost::get()
inphp artisan tinker
tinker console. After each fresh migration you can add--seed
method to run seederβs as well.php artisan migrate:fresh --seed
. This along with the fact that seeder can be used hand to hand with factory is what makes it so great.