2.

Add [~] to fillable property to allow mass assignment on [Ap

編集
この記事の要点
  • Laravel の Add [field] to fillable property to allow mass assignment
  • 原因: Model::create([...]) 等のマスアサインメントで渡したカラムが $fillable に含まれていない
  • 対処: Model に protected $fillable = ['name', 'email', ...]; を追加
  • セキュリティ上重要: 想定外のカラムへの不正代入を防ぐための仕組み

 

エラー内容

Add [~] to fillable property to allow mass assignment on [App\~].

Laravelで Eloquent モデル経由でレコードを作成・更新するとき、Model::create([...])Model::fill([...]) のような マスアサインメント を行った際に出るエラーです。Eloquent は意図しないカラムへの一括代入を防ぐため、対象カラムを fillable プロパティで明示する必要があります。

発生条件

  • Model::create(['name' => '...', 'email' => '...']) のように、配列で複数カラムを渡して保存している
  • 渡したキーが、モデルの $fillable 配列に登録されていない
  • 同じく fill()update()firstOrCreate()updateOrCreate() でも発生する

対処法

1. モデルに $fillable を追加(推奨)

マスアサインメントを許可するカラムをモデルに明記します。

// app/Models/User.php
class User extends Model
{
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
}

エラーメッセージ Add [~] to fillable property がここに追加すべきカラム名です。

2. $guarded を使う書き方

逆に「これだけは一括代入を禁止する」スタイルもあります。空配列にすると全カラム許可になります。

protected $guarded = ['id'];
// または全カラムを許可(非推奨)
protected $guarded = [];

3. 1カラムずつ代入する(一時的)

急ぎで動かしたい場合、マスアサインメントを避ければエラーは出ません。

$user = new User();
$user->name = 'Taro';
$user->email = 'taro@example.com';
$user->save();

$fillable と $guarded の使い分け

プロパティ意味適している場面
$fillable許可するカラムのホワイトリストセキュリティ重視。基本これが推奨
$guarded許可しないカラムのブラックリストカラム数が多くて列挙が現実的でない場合

注意点

  • $guarded = [] はマスアサインメントを完全に開放する設定。ユーザー入力をそのまま create($request->all()) に渡す前にバリデーションでカラムを絞ること
  • 新規カラムを追加したら $fillable も更新するのを忘れない
  • idcreated_atupdated_at は通常 $fillable に含めない
編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost'
  2. Add [~] to fillable property to allow mass assignment on [App\~].
  3. PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in ~
  4. Changing columns for table "~" requires Doctrine DBAL; install "doctrine/dbal"
  5. MethodNotAllowedHttpException No message
  6. Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
  7. production.ERROR: No application encryption key has been specified.
  8. Dotenv values containing spaces must be surrounded by quotes.
  9. Laravel \ Socialite \ Two \ InvalidStateException
  10. The page has expired due to inactivity. Please refresh and try again.
  11. Failed to clone https://github.com/symfony/thanks.git via https, ssh protocol
  12. Illegal offset type
  13. Cannot access protected property Illuminate\Http\Request::$...
  14. Emitted value instead of an instance of Error
  15. 画像保存時にInternal Server Error
  16. Failed to authenticate on SMTP server with username ...
  17. PostTooLargeException
  18. Database hosts array is empty.
  19. Invalid request (Unsupported SSL request)
  20. does not comply with psr-4 autoloading standard. Skipping.
  21. MySQLのSTR_TO_DATE関数を使用するとnullが返却される問題