Laravel 5.5 MassAssignmentException
Explanation of this error
This is a security feature of Laravel. It is designed to protect you against form manipulation when using mass assignments.
For example on a sign-up form: When you have an is_admin
column in your database, a user simply could manipulate your form to set is_admin
to true
on your server, and therefore in your database. This security feature prevents that by using a whitelist to define safe fields.
How to fix that
You need to set a $fillable
property on your model. It's value must be an array containing all fields that are safe to mass assignable (like username, email address, ...).
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Comment extends Model{ # This property! protected $fillable = ['body']; // ...}
See "Mass assignment" in the docs:https://laravel.com/docs/5.5/eloquent#mass-assignment
Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like what you did here:
public function addComment($body){ $this->comments()->create(compact('body'));}
You need to add the field you are populating to the fillable array in Comments.php
model:
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Comment extends Model{ protected $fillable = ['body']; public function post() { return $this->belongsTo(Post::class); }}
As the documentation states:
You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
Hope this helps you.