Class based model factories in Laravel 8 CODE
create a new factory for the Book model using the following Artisan command
php artisan make:factory BookFactory --model=Book
.it would generate a
 BookFactory.php
file under
database/factories 
which looks like so.
<?php

namespace Database\Factories;

use App\Models\Book;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class BookFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Book::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
        ];
    }
}
define the definition method like so.
public function definition()
{
    return [
        'title' => $this->faker->name,
        'author' => $this->faker->name,
        'published' => 1
    ];
}
Using the factories Once the
BookFactory 
is created, it’s now ready to be used. For instance, we can use it in the
database/seeders/DatabaseSeeder.php
class like so.
<?php

namespace Database\Seeders;

use App\Models\Book;
use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        Book::factory(5)->create();
    }
}
Notice, you can now directly use the factory on the model instance (App\Models\Book in this case) that is because when you create a model using the
php artisan make:model Book
Artisan command in Laravel 8, it generates the model which includes the new
HasFactory
trait. So, our Book model looks like so.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
}
by გიორგი ბაკაშვილი
4 years ago
Laravel
Factory
0
Pro tip: use ```triple backticks around text``` to write in code fences