0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel Seeder 実行前に全テーブルデータを削除する

Last updated at Posted at 2023-10-20

環境

  • PHP: 8.2.11
  • Laravel: 10.16.1
  • MySQL: 8.0.32

背景

$ php artisan db:seed

連続して実行すると場合によっては重複レコードが生成されて困る。

$ php artisan migrate:fresh --seed

これで解決するがマイグレーションファイルが増えるとすごく時間がかかってしまう。

解決方法

シーダー実行前に全テーブルをtruncateする。

準備

$ composer require doctrine/dbal

このライブラリがないとデータベースの全テーブル名を取得できずエラーになります。

DatabaseSeeder.php を編集

database/seeders/DatabaseSeeder.php
<?php

declare(strict_types=1);

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Foundation\Application; // 追記
use Illuminate\Foundation\Testing\DatabaseTruncation; // 追記

final class DatabaseSeeder extends Seeder
{
    use DatabaseTruncation; // 追記

    public function __construct(protected readonly Application $app) // 追記
    {
    }

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->truncateTablesForAllConnections(); // 追記
        $this->call(UserSeeder::class);
    }
}

使い方

$ php artisan db:seed

補足: DatabaseTruncation トレイト

テストの時に使用するトレイトです。
データベースの全てのテーブルデータを削除してくれます。(migrations テーブルを除く)

参考

昔書いた記事のアップデートです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?