Factory berguna untuk mengetest dengan cara populate database kita dengan data dummy atau data palsu.
Laravel menggunakan bantuan dari library FakerPHP/Faker.
Step 1 - Generate Factory File
php artisan make:factory NamaFactory
Step 2 - Masukkan Faker Sesuai Atribut Model
<?php
namespace Database\Factories;
use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;
class CompanyFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Model::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
$name = $this->faker->company;
return [
'user_id' => User::inRandomOrder()->first()->id,
'name' => $name,
'slug' => Str::slug($name, '-'),
'phone_number' => $this->faker->phonenumber,
'building_name' => $this->faker->buildingnumber,
'street_address1' => $this->faker->StreetAddress,
'city' => $this->faker->city,
'country' => $this->faker->country,
'postcode' => $this->faker->postcode,
];
}
}
Step 3 - Generate Data with Tinker
> php artisan tinker
App\Models\NamaModel::factory()->count(3)->make();
Top comments (0)