Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Laravel factory without a model?

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.

like image 924
Dr. Chocolate Avatar asked Aug 21 '17 23:08

Dr. Chocolate


People also ask

What is the difference between seeder and factory in Laravel?

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.

Does Laravel model have factory?

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.

What is factory model in Laravel?

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.

How do you call a factory in a seeder?

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.


2 Answers

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.

like image 188
Christian Dominguez Avatar answered Sep 20 '22 02:09

Christian Dominguez


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

like image 38
osama Abdullah Avatar answered Sep 21 '22 02:09

osama Abdullah