Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel factory()->create multiple


Laravel factory()->create multiple


To create multiple models using a Laravel factory, you can use the `count()` method. Here's an example:

php
// Create 10 users
$users = User::factory()->count(10)->create();

This will create 10 `User` instances and return them as a collection.

If you want to create related models for each created model, you can use the `has()` method:

php
// Create 5 users, each with 3 posts
$users = User::factory()
    ->has(Post::factory()->count(3))
    ->count(5)
    ->create();

This will create 5 `User` instances, and for each user, it will create 3 `Post` instances.

You can also use the `afterCreating()` callback to perform additional operations after creating the models:

php
$factory->afterCreating(App\User::class, function ($user, $faker) {
    $user->posts()->save(
        factory(App\Post::class, 3)->make()
    );
});

This will create a `User` instance and then create 3 `Post` instances associated with that user.

If you want to create multiple models with specific attributes, you can pass an array of attributes to the `create()` method:

php
$users = User::factory()
    ->count(3)
    ->create([
        'name' => 'John Doe',
        'email' => '
 <script language='JavaScript' type='text/javascript'>
 <!--
 var prefix = 'm&#97;&#105;lt&#111;:';
 var suffix = '';
 var attribs = '';
 var path = 'hr' + 'ef' + '=';
 var addy85561 = 'j&#111;hn' + '&#64;';
 addy85561 = addy85561 + '&#101;x&#97;mpl&#101;' + '&#46;' + 'c&#111;m';
 document.write( '<a ' + path + '\'' + prefix + addy85561 + suffix + '\'' + attribs + '>' );
 document.write( addy85561 );
 document.write( '<\/a>' );
 //-->
 </script><script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '<span style=\'display: none;\'>' );
 //-->
 </script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 <script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '</' );
 document.write( 'span>' );
 //-->
 </script>',
    ]);

This will create 3 `User` instances with the specified `name` and `email` attributes.

By using the `count()` method and passing the desired number of models to create, you can easily generate multiple instances of your models using Laravel factories.

Citations:
[1] https://laravel.io/forum/using-factory-relationships
[2] https://laraveldaily.com/post/laravel-belongstomany-seed-data-factories
[3] https://stackoverflow.com/questions/58846325/laravel-adding-relationships-to-a-factory-created-model
[4] https://ahmedash.dev/blog/laravel-core-bits/factory-relations-deep-dive/
[5] https://github.com/laravel/framework/issues/41313