I'm controller testing and essentially want to define a factory
to represent a post from the internet.
This post gets split up into several models in the controller.
I'm functional testing the whole controller though so how do I create a factory
without a model to represent a front end post?
It appears factory
are made like this:
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
Its the App\Models\User::class
that's throwing me. I want a generic one that's not tied to the User
model or any model.
Database seeder is used to populate tables with data. Model factories is a convenient centralized place to define how your models should be populated with fake data.
Laravel has a feature called model factories that allows you to build fake data for your models. It is very useful for testing and seeding fake data into your database to see your code in action before any real user data comes in.
As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define a definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory.
we need to create create factory class with following command. * The name of the factory's corresponding model. * Define the model's default state. Now we are ready to run seeder.
You would have to generate create a Query Builder instance in the seeder. So, for example, you want sample data in the balloons table :
DB::table('table_name')->insert(
[
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10)
]
);
And you would have to do this for every row you want to insert into your given table. You wouldn't worry about the model factory since there isn't a model.
you can use Faker that already comes with laravel
use Faker\Factory;
$faker = Factory::create();
then use the faker as you use it in factories with models in laravel
i did that in seeder class
here what i did
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With