User::factory() code example
Example 1: create a user using factory laravel
1. Create a factory:
php artisan make:factory ItemFactory --model=Item
Import Illuminate\Database\Eloquent\Factories\HasFactory trait to your model:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
use HasFactory;
}
2. Use it like this:
$item = Item::factory()->make();
$items = Item::factory()->count(3)->make();
3. Use create method to persist them to the database:
$item = Item::factory()->create();
$items = Item::factory()->count(3)->create();
Example 2: laravel factory relations data
factory(App\User::class, 30)->create()->each(function($user) {
$entity = factory(App\Entity::class)->make();
$address = factory(App\Address::class)->create([
'entity_id' => $entity
]);
$user->entities()->save($entity);
});