Home > database >  Laravel Model::create mass assignment not working for columns with null as default value
Laravel Model::create mass assignment not working for columns with null as default value

Time:02-02

I have a table in my db where some columns are nullable and of course have null as default value.

In my controller, I use Model::create($request->all()) to save. While it saves the data, the nullable columns were not populated with any value, still null.

Perhaps, does making it ->nullable() in migration the issue?

If not, can someone explain why the nullable columns were not populated with their corresponding values? and how do I address the problem?

CodePudding user response:

Take look at the Mass Assignment Documentation

So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model

You have to add $fillable property to your model, especially when you are using Model::create($request->all()).

public $fillable = [];

For example:

public $fillable = ['some_property', 'some_other'];

Now, if you will call create method, 'some_property' and 'some_other' will be assigned.

Also, you can use $guarded which says that all properies are mass assignable and nothing is guarded

public $guarded= [];

Don't use $guarded if you are going to create model by passing $request->all() to create method

  •  Tags:  
  • Related