Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create a model with Eloquent create method. Error telling MassAssignMentException

I have created a model named, Author. I tried creating a model with the help of eloquent create method like 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 am sure I am not mistaken with typo. When I run this, models is not created and says MassAssignmentException.

But when I tried with the following method, the model is created and was saved 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, its just looks much cleaner and simpler.

like image 279
Nirmalz Thapaz Avatar asked Sep 09 '13 13:09

Nirmalz Thapaz


2 Answers

this should work for you:

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

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

2) use the below code to fire the mass asssignment mechanism

$author = new Author;
$author->fill(Input::all());
$author->save();
like image 101
Gadoma Avatar answered Oct 25 '22 06:10

Gadoma


I was getting the MassAssignmentException when I have extends my model like this.

class Author extends Eloquent {

}

I was trying to insert array like this

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

Issue has been resolve when I created Author Model as given below.

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

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

like image 3
Amit Garg Avatar answered Oct 25 '22 05:10

Amit Garg