DEV Community

AquaCat
AquaCat

Posted on

【Laravel】How important it is to set "fillable" or "guarded" in model files

*Version of Laravel ...8.83.26

In Laravel, when you make model you need to add "fillable" or "guarded" to store/update records.
The columns that are set in "$fillable" are supposed to be mass assigned. "$guarded" is opposite. (These are used to block malicious request in mass assignment.)

Here is an example code for controller and model.

//BookController.php
public function store(Request $request){
  $book=Book::create($request->all());
...}
Enter fullscreen mode Exit fullscreen mode
//BookModel.php
...
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable=[
        'title','author'
    ];
}
Enter fullscreen mode Exit fullscreen mode

In your browser, you input the title and author of the book and click "submit" button.

What happens if you forget to add "$fillable" or "$guarded"?

If you forget to add "$fillable" or "$guarded", you will get an error as below. That means, you must set either of them.

[2022-11-23 08:23:14] local.ERROR: Add [title] to fillable property to allow mass assignment on [App\Models\Book].

What happens if you have misspelling in $fillable?

If you have a misspelling...('autor' should be 'author') in "$fillable", for example,

    protected $fillable=[
        'title','autor'
    ];
Enter fullscreen mode Exit fullscreen mode

you will get an error, of course.

[previous exception] [object] (PDOException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'author' doesn't have a default value at...

What if you set "$guarded"?

On the other hand, if you set "$guarded",

    protected $guarded=[
        'title','author'
    ];
Enter fullscreen mode Exit fullscreen mode

you will have an error because you tried to store(insert) data into the DB despite that data in the columns ('title','author') are not supposed to beassigned.

[2022-11-22 09:54:04] local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into books (updated_at, created_at) values (2022-11-22 09:59:33, 2022-11-22 09:59:33))

Tips

Those error massages always start with "Field '' doesn't have a default value." So, if you find this phrase in your error log, check your "$fillable" or "$guarded" settings in model files to make sure that you did not forget to set them, or the name of the columns are correct.

Top comments (0)