Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 MassAssignmentException

I'm following the Laravel From Scratch tutorial series, I'm currently at the part that you are creating a comment system for your articles system. But I'm having a problem, I don't really know what the error is saying at this point.

The error:

Illuminate\Database\Eloquent\MassAssignmentException
body

The comment model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

The post model:

<?php

namespace App;

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

    public function addComment($body)
    {
        $this->comments()->create(compact('body'));
    }
}

The route I made:

Route::post('/posts/{post}/comments', 'CommentsController@store');

The comments controller:

<?php

namespace App\Http\Controllers;

use App\Post;

class CommentsController extends Controller
{
    public function store(Post $post)
    {
        $post->addComment(request('body'));

        return back();
    }
}

Thanks in advance!

like image 948
Dion Pool Avatar asked Dec 10 '22 09:12

Dion Pool


1 Answers

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, ...).

<?php

namespace 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

like image 118
festie Avatar answered Dec 28 '22 22:12

festie