我正在使用 Laravel 4,我有一个显示帖子的页面,例如example.com/posts/1 显示数据库中的第一篇文章。
我想要做的是,如果有人尝试访问不存在的网址,则将页面重定向到索引。
例如如果没有帖子编号 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;
然后在你的 show($id) 方法中:
try
{
$post = $this->post->findOrFail($id);
return View::make('posts.show', compact('post'));
}
catch(ModelNotFoundException $e)
{
return Redirect::route('posts.index');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)