factory states code example
Example 1: php artisan make factory
php artisan make:factory AddressFactory --model="App\\Address"
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