mass assignment on [App\comment] in laravel

Viewed 82

trying to add a comment in my blog , so i got this new error :

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

this is thr controller :

public function store  (blog $getid)
{
    comment::create([
        'body' =>request('body'),
        'blog_id'=> $getid->id
    ]);

     return view('blog');
}

and this is the form :

<form method="POST" action="/blog/{{$showme->id}}/store" >
   @csrf
   <label> Commentaire </label> </br>
   <textarea name="body" id="" cols="30" rows="2"></textarea> </br>
   <button type="submit"> Ajouter commentaire</button>
</form>

web.php :

Route::post('blog/{getid}/store', 'commentcontroller@store');
1 Answers

To avoid filling in any given property, Laravel has mass asignment protection. The properties you want to be filled should be in the $fillable property on the model.

class Comment {
    $fillable = ['body', 'blog_id'];
}

Bonus

For keeping up with standards. You should not name your classes in lower case, it should be Blog and Comment, both in PHP code and in file name.

Id should not be filled but associated, so they will be loaded properly on the model. So imagine your Comment model having the blog relationship.

class Comment {
    public function blog() {
        return $this->belongsTo(Blog::class);
    }
}

You should assign it instead. Where you would get the Blog by using Model binding, therefor you should name the parameter $blog so the binding will work. Additionally using Request dependency injected, is also a good approach.

use Illuminate\Http\Request;

public function store(Request $request, Blog $blog) {
    $comment = new Comment(['body' => $request->input('body')]);
    $comment->blog()->associate($blog);
    $comment->save();
}
Related