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

Deadly 提交于 2019-12-05 00:08:10

问题


I'm working with Laravel 4, I have a page that shows posts e.g. example.com/posts/1 shows the first post from the db.

What I want to do is redirect the page to the index if someone tries to go to a url that doesn't exist.

e.g. if there was no post number 6 then example.com/posts/6 should redirect to example.com/posts

Here is what I have, is it on track at all?

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');
        }
}

Any ideas? Thanks :)


回答1:


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');
}



回答2:


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.



来源:https://stackoverflow.com/questions/17483233/laravel-4-using-controller-to-redirect-page-if-post-does-not-exist-tried-but

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