有一个资源丰富的控制器,其__contruct
函数可以声明$project
public function __construct(Project $project){
$this->project = $project;
}
然后我有update
和destroy
函数给出了
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');
}
我做错了什么?
答案 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以自动从数据库中获取模型。