为什么模型中的值不会在数据库中更新?

时间:2016-11-29 09:34:17

标签: php mysql laravel-5

我将使用我的控制器中的addpermission函数插入和更新值

public function addPermission(Request $request, $id, $permission = null) 
{
  $this->validate($request, [
    'status'   => 'required'
  ]);

  if(is_null($permission)) {
    $permission = new Permission;
    $msg = 'Permission has been added to your Collaborator successfully';
  } else {
    $permission = Permission::findOrFail($permission,['id'])->id;
    $msg = 'Permission updated successfully';
  }

  $permission->status = $request->input('status');
  $permission->project_id       = $id;
  $permission->collaborator_id =  $request->input('cid');
  $permission->save();
  return redirect()->back()->with('info', $msg);
}

我的路线

Route::post('projects/{project_id}/permission', [
    'uses' => 'ProjectCollaboratorsController@addPermission',
    'as'   => 'projects.collaborators.permission',
  //  'middleware' => ['auth']
]);

数据插入正常,但更新无效 当我点击按钮进行更新时,它会作为新记录插入数据库。

我的表名是权限,并有以下列

  • id(autoincrement)
  • 状态
  • PROJECT_ID
  • collaborator_id

我需要更改哪些内容才能进行更新?

3 个答案:

答案 0 :(得分:1)

我在这一行看到一个错误,这应该返回权限对象而不是权限id。

$ permission = Permission :: findOrFail($ permission,['id']) - > id; 改成, $ permission = Permission :: findOrFail($ permission ['id']);

答案 1 :(得分:0)

你应该写这个。希望这将解决您的问题

public function addPermission(Request $request, $id, $permission) 
{
  $this->validate($request, [
    'status'   => 'required'
  ]);
  $per = Permission::where('id', $permission)->first();

  if(is_null($permission)) {
    $permission = new Permission;
    $msg = 'Permission has been added to your Collaborator successfully';
  } else {
    $permission = Permission::findOrFail($per)->id;
    $msg = 'Permission updated successfully';
  }

  $permission->status = $request->input('status');
  $permission->project_id       = $id;
  $permission->collaborator_id =  $request->input('cid');
  $permission->save();
  return redirect()->back()->with('info', $msg);
}

答案 2 :(得分:0)

我认为你可能需要在权限id中添加一个可选的路由参数。

Route::post('projects/{project_id}/permission/{permission_id?}', [
    'uses' => 'ProjectCollaboratorsController@addPermission',
    'as'   => 'projects.collaborators.permission',
  //  'middleware' => ['auth']
]);