In the process of building application, it is important to test with proper database. You can't manually create dummy database manually and test. You need to use any tool which creates required data.
Laravel ships out of the box solution for that. Laravel provides to create Factory for model and create as many fake data as you want. In this article, we will create Dummy data for Transaction model.
Suppose you have have payment application with lots of transactions data, your Transaction model has few fields which you want to create dummy data. First of all, create Factory for the model using below command.
php artisan make:factory TransactionFactory --model=Transaction
This will create a new factory class at /database/factories
folder. Now open the file and add the fields in definition() with the datatype. You can find appropriate format for any field data at Faker documentation.
Now you need to run the factory to create fake database. Make sure your model use Illuminate\Database\Eloquent\Factories\HasFactory
trait. You can do this either from laravel tinker command or from the database seeder class.
To run tinker command, first open Terminal and start laravel tinker
php artisan tinker
Now run the command to create dummy data. You can create as many records as you pass number in factory()
method.
\App\Models\Transaction::factory(100)->create();
The second way is to run seeder. Laravel application already have one seeder class at /database/seeders/DatabaseSeeder.php
. In the run()
method you can add the above line.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
\App\Models\Transaction::factory(100)->create();
}
}
And from the Terminal run the command to run seeder which will trigger Factory.
php artisan db:seed --class=DatabaseSeeder
This way you can create fake data in Laravel. I hope you liked this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Find the Sum of an Array of Numbers in JavaScript
Use the JavaScript reduce() Method Yo...How to get the value of a textarea in jQuery
Use the jQuery val() method You can u...Real Time Comment System With Laravel And Vuejs
Today, Laravelcode share sommething new...How to make Laravel Auth help of laravel-ui Package
You might have descried after installing...How to Generate Unique slug in Laraval 7.x Example
Want to engender unique slug in Laravel?...