Failed to create model using the Eloquent creation method. MassAssignMentException message error

I created a model called Author. I tried to create a model using an eloquent creation method similar to this:

public function postCreate(){ Author::create(array( 'user' => Input::get('user'), 'info' => Input::get('info') )); return Redirect::to('authors') ->with('message', 'User created successfully'); } 

'user' and 'info' are the name of the form elements. I'm sure I'm not mistaken with typos. When I run this, models are not created and they say MassAssignmentException.

But when I tried using the following method, the model is created and stored in the table

 public function postCreate(){ $author = new Author; $author->name = Input::get('user'); $author->info= Input::get('info'); $author->save(); return Redirect::to('authors') ->with('message', 'User created successfully'); } 

And I really want to use the create method, it just looks a lot cleaner and simpler.

+4
source share
5 answers

this should work for you:

1), as already indicated in @fideloper and @ the-shift-exchange, in your Author model you need to create the field below (this is a white list of all the database columns that you want to use for autopopulation [mass assignment])

  protected $fillable = array('user','info', ... ,'someotherfield'); 

2) use the code below to start the mass compression mechanism.

 $author = new Author; $author->fill(Input::all()); $author->save(); 
+10
source

I get a MassAssignmentException when I extend my model as follows.

 class Author extends Eloquent { } 

I tried to insert an array like this

 Author::create($array);//$array was data to insert. 

The problem was solved when I created the authorโ€™s model, as shown below.

 class Author extends Eloquent { protected $guarded = array(); // Important } 

Link https://github.com/aidkit/aidkit/issues/2#issuecomment-21055670

+3
source

You need to set the Mass Assignment fields. In your author model:

class Author extends Eloquent {

 protected $fillable = array('name', 'bio'); 

}

+2
source

Your model must have the $ fillable variable set.

See the mass-assignment documentation for more details.

In your model, the author will look something like this:

 protected $fillable = array('user', 'info'); 
+1
source

You need to use the protected $fillable , assigning it an array of fields / columns that you want to fill / assign values. For example, you have a model with fields f1, f2, f3 and f4 . You want to assign the values f1, f2 and f3 but not to f4 , then you need to use:

 protected $fillable = ['f1', 'f2', 'f3']; 

The above line will allow you to pass an array:

 $mod = Model::create($arr); $mod->save(); 

Regardless of the $ arr array, only f1, f2, and f3 will be assigned values โ€‹โ€‹(if the values โ€‹โ€‹exist in the $arr array for f1, f2, f3 ).

Hope this helps you and others.

0
source

Source: https://habr.com/ru/post/1501309/


All Articles