Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Factory in Laravel 5.5

I ran below command

php artisan make:factory AddressFactory

I am getting below result

$factory->define(Model::class, function (Faker $faker) {

But I would like to get result like below

$factory->define(App\Address::class, function (Faker $faker) {

What should I do ?

like image 709
abu abu Avatar asked Dec 18 '22 02:12

abu abu


2 Answers

If you want the make:factory command to generate a factory class for an existing model, you need to tell it which model to use with the --model option:

php artisan make:factory AddressFactory --model="App\\Address"
like image 161
jedrzej.kurylo Avatar answered Dec 20 '22 16:12

jedrzej.kurylo


For Laravel 8

With the artisan command, you no longer need to specify the model. By automatically including the factory trait in the model, Laravel automatically makes the factory methods available to the corresponding model.

So only:

php artisan make:factory AddressFactory

It is then sufficient to call the model in the seeder or in the tests.

For example:

App\Models\Address::factory(10)->create();

Model & Factory Discovery Conventions

Once you have defined your factories, you may use the static factory method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory trait in order to instantiate a factory instance for that model.

The HasFactory trait's factory method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the Database\Factories namespace that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, you may overwrite the newFactory method on your model to return an instance of the model's corresponding factory directly:

like image 33
Maik Lowrey Avatar answered Dec 20 '22 16:12

Maik Lowrey