5
votes

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 :)

2

2 Answers

10
votes

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

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.