[Laravel]seeder備忘録

 
seeder作成

sail artisan make:seeder PostSeeder

 
PostSeeder.php追記

public function run(): void
{
    \App\Models\Post::create([
        'title'   => 'あいうえお',
        'body'    => 'かきくけこ',
        'user_id' => 1,
    ]);
}

 
PostSeeder実行

sail artisan db:seed --class=PostSeeder

 
factory作成

sail artisan make:factory PostFactory

 
PostFactory

public function definition(): array
{
    return [
        'title'   => fake()->text(20),
        'body'    => fake()->text(50),
        'user_id' => \App\Models\User::factory(),
    ];
}

 
必要なら.env修正

'faker_locale' => 'ja_JP'

 
DatabaseSeeder.php修正

use App\Models\Post;

runメソッドにある元ソースは削除

public function run(): void
{
    Post::factory(3)->create();
}

 
DatabaseSeeder実行

sail artisan db:seed

 
エラー「Call to undefined method App\Models\Post::factory()」の対処
Models\Post.phpに下記を追記

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;
}