我正在使用Laravel Framework 5.5.22
。
我在我的数据库中有用户和任务。我的任务有以下架构:
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->timestamps();
});
我的用户模型如下所示
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function task()
{
return $this->hasMany('App\Task');
}
}
我想将用户的任务存储在数据库中。请参阅下面我尝试的商店方法:
public function store(Request $request)
{
$this->validate($request, [
'newTaskName' => 'required|min:3|max:190',
]);
Auth::user()->task()->Create($request->all()); //here I get the error
Session::flash('success', 'New task has been successfully added.');
return redirect()->route('tasks.index');
}
但是,我在此行Auth::user()->task()->Create($request->all());
收到以下错误:
Illuminate\Database\Eloquent\MassAssignmentException _token
为什么请求未正确安全的任何建议?
答案 0 :(得分:1)
使用->except()
方法代替all()
:
Auth::user()->task()->create($request->except('_token'));
答案 1 :(得分:1)
尝试使用DB
$insertData = [
"name" => $request->name,
"user_id" => \Auth::id()
];
DB::table('tasks')->insert($insertData);
或者,如果您将模型创建为Task
$task = new Task($insertData);
$task->save();
答案 2 :(得分:0)
在任务模型中添加以下行:
protected $guarded = ['_token'];