💥

LaravelのmigrateでA table was not found: You might have forgotten to run

2022/05/23に公開

問題:php artisanコマンドが実行できない状態になる。
解決策:
Providers/xxxxServiceProviderのbootにデータベースから取得するコードが無いか確認し
テーブルの存在有無をチェックする。

 Illuminate\Database\QueryException 
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'xxx' doesn't exist (SQL: select * from `xxx`)
  • A table was not found: You might have forgotten to run your migrations. You can run your migrations using `php artisan migrate`.
    https://laravel.com/docs/master/migrations#running-migrations

下記のようなコードがあるとする。これを

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $permissions = Permissions::all();
    }
}

下記の通りにテーブルの存在有無をチェックする

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (Schema::hasTable('permissions')) {
            $permissions = Permissions::all();
        }
    }
}

なぜこのようなエラーが起きるのか?

開発時は

  1. 開発者はpermissionsテーブルを作成
  2. php artisan migrateを実行
  3. bootに記載のある処理が実行される
  4. migrationsのファイルに従ってmigrateされる
  5. AuthServiceProvider.phpにPermissions::all()を追加

という手順で、すでにテーブルが存在しているためエラーは出ない

新たにプロジェクトをクローンする時は

  1. php artisan migrateを実行
  2. bootに記載のある処理が実行される
  3. テーブルが存在しないためエラー

という手順で、テーブルが存在しないためエラーが出る

エラーメッセージを読んでも原因が全く推察できないのでハマりやすい。

関連:
https://stackoverflow.com/questions/54077478/check-table-exist-in-authserviceprovider
https://github.com/laracasts/laravel-5-roles-and-permissions-demo/pull/6

Discussion