L5:在非对象上调用成员函数function()

时间:2015-05-15 08:17:41

标签: php laravel

有一个资源丰富的控制器,其__contruct函数可以声明$project

 public function __construct(Project $project){

    $this->project = $project;
}

然后我有updatedestroy函数给出了 Call to a member function delete() on a non-object(或update()错误)

 public function edit($id)
{
    $project = $this->project->find($id);
    return view('project.edit', ['project' => $project, 'id' => 'edit']);
}


public function update(CreateProjectRequest $request, $project)
{
    $project->fill($request->input())->save();

    return redirect('project/index');
}


public function destroy($project)
{
    $project->delete();
    return redirect('project');
}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

在这种情况下,

$project只是项目的ID。你必须先加载它:

public function destroy($projectId)
{
    $project = $this->project->findOrFail($projectId);
    $project->delete();
    return redirect('project');
}

或者只使用以密钥作为参数的destroy方法:

public function destroy($projectId)
{
    $this->project->destroy($projectId);
    return redirect('project');
}

您可能还想查看Route Model Binding以自动从数据库中获取模型。