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?

More than 3 years have passed since last update.

【Laravel】Eloquent:複数代入時の$guardedの使い方についての備忘録

Posted at

#開発環境
PHP7.3
Laravel5.8
MySQL8.0

#フォームから送信した値を保存する時などに、「値を用意しない項目」を$guardedで指定する

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    protected $guarded = ['id'];
}

// データ保存時に['id']は除かれる
// フォーム側で['id']を送信しなくともnullエラーが起きない

#逆に、「この値のみを保存したい」という時は$fillableで指定する

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    protected $fillable = ['chat_room_id', 'context', 'post_user_info_id'];
}

// 送信した値の中から、'chat_room_id', 'context', 'post_user_info_id'のみを保存し、それ以外の値は除かれる

#まとめ
指定時の挙動から、
$fillableは「ホワイトリスト」
$guardedは「ブラックリスト」
と言われているらしい。

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?