6
6

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

【Laravel】php artisan migrateをしたときに出くわしがちなエラー【ただのDBエラー】

Last updated at Posted at 2020-02-20

Laravel: php artisan migrateをしたときに出くわしがちなエラー

エラー例

外部キーの型が一致しない

外部キーを付けるフィールドの型と参照先フィールドの型が一致していないとデータベースエラーが起こります。
特にLaravel5.8以降では主キーの型はデフォルトでUNSIGNED BIGINTになっています。
外部キーの型がINTEGERのままだとこのエラーに遭遇します。

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 3780 Referencing column 〜

対策

マイグレーションファイルの型を揃える。

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->string('id')->primary();
            // $table->unsignedInteger('user_id'); // user.idがINTEGERならこちら
            $table->bigInteger('user_id')->unsigned(); // user.idがUNSIGNED BIGINTならこちら
            $table->string('filename');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

参考: Laravel 5.8 にて["SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint"]エラー - Qiita

すでにテーブルが存在する

Illuminate\Database\QueryException  : SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'photos' already exists 〜

中途半端にテーブルが残っているとよく出くわします。
php artisan migrateに失敗すると中途半端にテーブルができることがあります。
(私は上記の「外部キーの型が一致しない」の事例でまさに中途半端なテーブルができました。)

対策

「:fresh」をコマンドの最後に付けることで既存のテーブルを消して作り直すので回避できます。
※全テーブルの中身が消えるので十分に注意してください

php artisan migrate:fresh

参考: Laravel の migrate で Base table or view already exists というときに、migrate:refresh した - Qiita

あるいは、直接テーブルを消してもよいでしょう。

コントローラファイルが見つからない

ErrorException (E_WARNING)
include(/hogehoge/backend/vendor/composer/../../app/Http/Controllers/元のコントローラをコピーして作ったファイル名.php): 
failed to open stream: No such file or directory

CompaniesController.phpを複製して、CompaniesController-.phpを作りました。
オートローダーの設定が変になっていたので、プロジェクトルートから下記コマンドで修正しました。

composer dump-autoload

php artisan migrateの影響かはわかりませんが、コマンド実行後、もとのコントローラをいくらさわっても反映されないのでコピーしたファイルを消すと上記のエラーが発生しました。

下記に同じ現象の解決法が記載されていました。

Laravel 5.7でControllerのファイル名を少し変更(大文字)しただけなのに、Controllerファイルが見つからないエラーが出るようになった - Qiita

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?