laravel 在非对象上调用成员函数 delete()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28146358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function delete() on a non-object
提问by CIPSR
Im trying to delete value form web page but get an error
我试图删除值表单网页但收到错误
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Call to a member function delete() on a non-object
Here's my controller code:
这是我的控制器代码:
public function delete(){
$id=Input::get('id');
$galleries=ForumGallery::find($id);
$galleries->delete();
return Redirect ::route('gallery',$id);
}
And the according route:
以及相应的路线:
Route::get('/Gallery/delete',array('uses'=>'GalleryController@destroy','as'=>'d??estroy'))
how to solve it?
如何解决?
回答by kapa89
You should check $galleries before delete it:
你应该在删除它之前检查 $galleries :
$galleries=ForumGallery::find($id);
if (!is_null($galleries)) {
$galleries->delete();
}
回答by lukasgeiter
You need to check if a gallery has actually been found. Otherwise find()
returns null
:
您需要检查是否确实找到了画廊。否则find()
返回null
:
$galleries = ForumGallery::find($id);
if ($galleries) {
$galleries->delete();
}
Alternatively you can also use findOrFail()
which will throw an Exception if no model is found and handle that exception globally (e.g. to display a 404 error)
或者,您也可以使用findOrFail()
which 将在未找到模型时抛出异常并全局处理该异常(例如显示 404 错误)
$galleries = ForumGallery::findOrFail($id);
$galleries->delete();
Edit
编辑
Judging from the comment you left on the other answer, you call the route by /Gallery/delete/6
. If you want to do that you need to change your route:
从您在另一个答案上留下的评论来看,您通过/Gallery/delete/6
. 如果你想这样做,你需要改变你的路线:
Route::get('/Gallery/delete/{id}',array('uses'=>'GalleryController@destroy','as'=>'d??estroy'));
and controller method:
和控制器方法:
public function delete($id){
$galleries=ForumGallery::findOrFail($id);
$galleries->delete();
return Redirect ::route('gallery',$id);
}