13
4

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 3 years have passed since last update.

Laravel 7 で開発と本番のSeederクラスをサブフォルダに分ける

Last updated at Posted at 2020-04-23

#やりたいこと
開発用のSeederと本番での初期挿入のSeederを分けて使いたい

環境
Laravel7

#やりかた
フォルダ構成を下記のようにする

  • database
    • seeds
      • local
      • production

まずは適当なSeederクラスを作成して開発と本番のディレクトリにコピー

php artisan make:seeder HogeSeeder

サブディレクトリ内で同一のSeederクラス名をつけたかったのと、
IDEで呼び出すときに補完が効かなくなるので
名前空間を追加


<?php

namespace Database\Seeds\Local;#追加(本番要はLocalの箇所をProductionに)

use App\Hoge;
use Illuminate\Database\Seeder;

class HogeSeeder extends Seeder
{
    public function run()
    {
        factory(Hoge::class, 20)->create();
    }
}

あとはDatabaseSeederでよびだす

<?php

use Database\Seeds\Local;
use Database\Seeds\Production;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    const LOCAL = [
        Lcal\AreasTableSeeder::class,
    ];

    const PROD = [
        Production\OccupationsTableSeeder::class
    ];

    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        DB::transaction(function () {
            $this->call(App::isLocal() ? self::Local : self::PROD);
        });
    }
composer dump-autoload
13
4
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
13
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?