Inside this blog I will discuss with you how to use laravel faker package for inserting fake data. So for quick start, I should make a dummy model for laravel project. So let’s open CMD/terminal and paste this commands if you like so ….
Step 1: Creating up the table
php artisan make:migration create_orders_table
php artisan migrate

Now, looking inside at my ‘orders’ table, see below schema …
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('address');
$table->string('landmark');
$table->string('dropnote')->nullable();
$table->foreignId('userid')->references('id')->on('users')->cascadeOnDelete();
$table->timestamps();
});
Step 2: Setup the model and faker for the model.
php artisan make:model Order
Now, inside App/models/Order.php
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Order extends Model
{
protected $primaryKey = "id";
protected $table = "orders";
use HasFactory;
protected $fillable = ['first_name', 'last_name', 'address','landmark','userid'];
}
first of all clear it, that HasFactory ensure that this table will be enabled for fake data insertion. And also we should configure that which column will be filled by fake data!!
Step 3: Make factory file for the model and configure it as per needs.
php artisan make:factory OrderFactory --model=Order
Now, inside database/factories/OrderFactory.php see below code …
public function definition(): array
{
return [
'first_name' => fake()->firstName(),
'last_name' =>fake()->lastName(),
'address' => fake()->address(),
'landmark' => fake()->secondaryAddress(),
'userid' => rand(1, 5),
];
}
Now, last thing, go inside seeders/DatabaseSeeder.php and set the factory against it.
use App\Models\Order;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
Order::factory(25)->create();
}
}
Now, for seeding the database use command:
php artisan db:seed

Last thing to note, laravel by default uses phpfaker package: https://fakerphp.org/
