1
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 1 year has passed since last update.

【Laravelエラー】Add [ ] to fillable property to allow mass assignment on

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

Articleをcreateするとき下記のエラー

Add ['title'] to fillable property to allow mass assignment on
app/Models/Article.php
class Article extends Model
{
	use HasFactory;

	public function comments()
	{
		return $this->hasMany(Comment::class);
	}

	public function user()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function likes()
	{
		return $this->hasMany(Like::class);
	}
}

原因

modelにprotected $fillableを定義してないから。

ただし、createメソッドを使用する前に、モデルクラスでfillableまたはguardedプロパティを指定する必要があります。すべてのEloquentモデルはデフォルトで複数代入の脆弱性から保護されているため、こうしたプロパティが必須になります。

解決方法

app/Models/Article.php
class Article extends Model
{
	use HasFactory;

    #追記    
	protected $fillable = [
		'title',
		'content',
		'user_id'
	];

	public function comments()
	{
		return $this->hasMany(Comment::class);
	}

	public function user()
	{
		return $this->belongsTo(User::class, 'user_id');
	}

	public function likes()
	{
		return $this->hasMany(Like::class);
	}
}

Railsでいうと

Mass Assignment脆弱性の対策として

Laravel -> modelに$fillableを設定
Rails -> controllerにストロングパラメータを設定

ということかなと。
Railsから入ったのでその違いがわかるのが楽しい。

1
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
1
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?