Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add [title] to fillable property to allow mass assignment on [App\Post]

Tags:

php

laravel

While inserting data in Mysql I have encountered the following error:

"Add [title] to the fillable property to allow mass assignment on [App\Post]."

Here is my code:

$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);

While when I use another way to insert data, it is working fine: Following code is working fine :

//Create Post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
   

Could anyone explain why an upper portion of the code is throwing an error?

like image 862
Muhammad Mansha Avatar asked Dec 15 '18 13:12

Muhammad Mansha


4 Answers

Add a title to the fillable array in your model Post, to allow saving through creating and massive methods

protected $fillable = ['title'];
like image 147
Walter Cejas Avatar answered Nov 12 '22 08:11

Walter Cejas


The alternative to protected $fillable = ['title']; would be :

protected $guarded = [];  

and leave it as an empty array, without the need to define anything inside. It is the exact opposite of $fillable, sort of like telling the database to accept everything, except the fields you specify inside the $guarded array.

like image 29
Armin Avatar answered Nov 12 '22 07:11

Armin


For $fillable all

protected $guarded = ['id']; 
like image 14
Alimon Karim Avatar answered Nov 12 '22 07:11

Alimon Karim


For mass assignment you should define "Fillable array" in your model (App\Post)

So your model should be something like this:

    class Post extends Model
    {

        protected $fillable = ['title','body']; //<---- Add this line
// ... 
}

More information: [https://laravel.com/docs/5.7/eloquent#mass-assignment][1]

like image 8
Saman Ahmadi Avatar answered Nov 12 '22 06:11

Saman Ahmadi