我正在使用Laravel 4,我有一个显示帖子的页面,例如example.com/posts/1显示了数据库中的第一篇帖子。
如果有人试图转到一个不存在的url,我想做的是将页面重定向到索引。
例如,如果没有帖子编号6,则example.com/posts/6应重定向到example.com/posts
这是我的东西,它在轨道上吗?
public function show($id)
{
$post = $this->post->findOrFail($id);
if($post != NULL)
{
return View::make('posts.show', compact('post'));
}
else
{
return Redirect::route('posts.index');
}
}
有什么想法吗?感谢:)
正如Rob所解释的,您需要执行以下操作:
在文件顶部:
use Illuminate'Database'Eloquent'ModelNotFoundException;
然后在您的节目中($id)方法:
try
{
$post = $this->post->findOrFail($id);
return View::make('posts.show', compact('post'));
}
catch(ModelNotFoundException $e)
{
return Redirect::route('posts.index');
}
如果找不到页面,方法findOrFail()
将抛出异常。因此,如果将try { ... } catch() { ... }
封装在它周围,则可以返回重定向的视图。