问题
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