Josh
Josh

Reputation: 6139

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

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

Upvotes: 5

Views: 4190

Answers (2)

user2382985
user2382985

Reputation:

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

Upvotes: 10

Rob Gordijn
Rob Gordijn

Reputation: 6511

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.

Upvotes: 1

Related Questions