我试图删除值表单网页 但得到一个错误
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Call to a member function delete() on a non-object
这是我的控制器代码:
public function delete(){
$id=Input::get('id');
$galleries=ForumGallery::find($id);
$galleries->delete();
return Redirect ::route('gallery',$id);
}
和相应的路线:
Route::get('/Gallery/delete',array('uses'=>'GalleryController@destroy','as'=>'destroy'))
如何解决?
答案 0 :(得分:2)
您应该在删除它之前检查$ gallery:
$galleries=ForumGallery::find($id);
if (!is_null($galleries)) {
$galleries->delete();
}
答案 1 :(得分:1)
您需要检查是否确实找到了一个图库。否则find()
会返回null
:
$galleries = ForumGallery::find($id);
if ($galleries) {
$galleries->delete();
}
或者您也可以使用findOrFail()
,如果找不到模型将抛出异常并全局处理该异常(例如显示404错误)
$galleries = ForumGallery::findOrFail($id);
$galleries->delete();
根据您在另一个答案上留下的评论,您可以通过/Gallery/delete/6
拨打该路线。如果你想这样做,你需要改变你的路线:
Route::get('/Gallery/delete/{id}',array('uses'=>'GalleryController@destroy','as'=>'destroy'));
和控制器方法:
public function delete($id){
$galleries=ForumGallery::findOrFail($id);
$galleries->delete();
return Redirect ::route('gallery',$id);
}