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?
Add a title to the fillable array in your model Post, to allow saving through creating and massive methods
protected $fillable = ['title'];
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.
For $fillable all
protected $guarded = ['id'];
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With