Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 : MassAssignmentException in Model.php

I am getting this error:

MassAssignmentException in Model.php line 448: _token

When I am using create method. Please review code below:

Contacts.php (Model):

class Contacts extends Model
{
    protected $table = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
}

ContactsController.php (Controller):

public function store(Request $request)
{        
    $inputs = $request->all();
    $contacts = Contacts::Create($inputs);
    return redirect()->route('contacts.index');
}
like image 737
Sandeep Avatar asked Jan 02 '16 11:01

Sandeep


4 Answers

For the Mass Assignment Exception: you should specify all the fields of the model that you want to be mass-assignable through create or update operations on the property $fillable:

protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];

Besides, the field $table should contain only the model's table name:

protected $table = 'your_table_name';
like image 163
Moppo Avatar answered Nov 15 '22 04:11

Moppo


This might happen in case if you have used the wrongly imported the class. if you are using the User Model.

Wrong Import

// mostly IDE suggestion
use Illuminate\Foundation\Auth\User;

Correct Model Import

use App\User;

i have gone through this. might help someone.

like image 39
shakee93 Avatar answered Nov 15 '22 04:11

shakee93


You can all column fillable:

protected $guarded = array();

Add your model.

like image 43
Ferhat KOÇER Avatar answered Nov 15 '22 04:11

Ferhat KOÇER


You need only to add the following to your Model (Contact):

protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];

For example:

class Contacts extends Model { 
   protected $table = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at']; 
   protected $fillable = [ 'name', 'mobile', 'email', 'address', 'created_at', 'updated_at' ]; 
}
like image 30
Youssef Belyazidi Avatar answered Nov 15 '22 06:11

Youssef Belyazidi