0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelのnullableに気をつけること

Last updated at Posted at 2025-07-22

本日画像の保存処理を行っていたが、処理が通っているにも関わらず画像が保存されなかった。

原因

とてもシンプルでモデルに画像を保存するカラムを書き忘れたこと

protected $fillable = [
        'id',
        'user_id',
        'title',
        'author',
        'image_path',
    ];

image_path の記述忘れだった。

先日も同じようなミスで時間を消費してしまったので無念である。

ただ先日はエラーが出ていたが今回はエラーが出なかった。

エラーが出なかった原因

マイグレーションファイルの画像保存で以下のように書いていたため

public function up()
    {
        Schema::table('books', function (Blueprint $table) {
            $table->text('image_path')->nullable()->after('title');
        });
    }

nullableは値が入っていなくても処理を通す、故に保存できなくてもエラーを出さずにそのまま通すということだった。
$table->text('image_path');というようにnullableでなければおそらくNOT NULL制約のエラーが出て、もしかすると今回のミスに早いタイミングで気づいたかもしれない。

モデルの記述忘れのミスはこれで2回目であり、状況を変えてまた食らいそうな気がするので戒めとして記述。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?