Laravel 5 : MassAssignmentException in Model.php

2019-02-05 20:00发布

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');
}

6条回答
走好不送
2楼-- · 2019-02-05 20:42

Check Model you have Imported or Not. If not then use this.

<?php 

 namespace App\Http\Controllers\Auth; 
 use App\Http\Controllers\Controller; 
 use App\User;
查看更多
你好瞎i
3楼-- · 2019-02-05 20:43

You can all column fillable:

protected $guarded = array();

Add your model.

查看更多
贪生不怕死
4楼-- · 2019-02-05 20:46

If all of the above fails, you can try following.

Put following after namespace.

use Eloquent;

Put following at the start of your store method.

Eloquent::unguard();

like:

public function store(Request $request)
{        
   Eloquent::unguard();
   $inputs = $request->all();
   $contacts = Contacts::Create($inputs);
   return redirect()->route('contacts.index');
}

This is not recommended though, as this makes things vulnerable to attacks. But if you need a quick fix this might help.

查看更多
劫难
5楼-- · 2019-02-05 20:48

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.

查看更多
神经病院院长
6楼-- · 2019-02-05 20:48

Make sure you are putting the $fillable or $guarded in the app\Contacts.php file and not the app\Http\Controllers\ContactsController.php file. It should be obvious, but it can be overlooked.

查看更多
成全新的幸福
7楼-- · 2019-02-05 21:00

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';
查看更多
登录 后发表回答