factory laravel 8 code example

Example 1: laravel factory

php artisan make:factory PostFactory --model=Post

Example 2: 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(); // Create a single App\Models\Item instance

	// or

	$items = Item::factory()->count(3)->make(); // Create three App\Models\Item instances

3. Use create method to persist them to the database:

  $item = Item::factory()->create(); // Create a single App\Models\Item instance and persist to the database

  // or

  $items = Item::factory()->count(3)->create(); // Create three App\Models\Item instances and persist to the database

Example 3: make model factory and controller laravel

php artisan make:model ModelName -a
// -a stands for all (Model, Controller, Factory and Migration)
// Note: The above command will work successfully in Laravel 5.5 or > versions

Example 4: 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);
});

Example 5: add factory data laravel

For Laravel version 7.* and less
factory(App\User::class, 3)->make();

Use create method to persist them to the database:
factory(App\User::class, 3)->create();

Tags:

Php Example