Laravel 4: using controller to redirect page if post does not exist - tried but failed so far

荒凉一梦 提交于 2019-12-03 16:02:45

Exactly as Rob explained, you will need to do the following:

At the top of your file:

use Illuminate\Database\Eloquent\ModelNotFoundException;

Then within your show($id) method:

try
{
    $post = $this->post->findOrFail($id);

    return View::make('posts.show', compact('post'));
}
catch(ModelNotFoundException $e)
{
    return Redirect::route('posts.index');
}

The method findOrFail() will throw an Exception if the page is not found. So if you wrap a try { ... } catch() { ... } around it, you can return a view of a redirect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!