Imagine there is the following url structure:
someurl.axyz/{post-slug}
someurl.axyz/{page-slug}
post-slug
and page-slug
are stored in the unique database table column. What is the "most" elegant way to handle the routes with Laravel 4.2 (and if there is a difference the way with Laravel v5.2)?
I resolved this using binding parameter to a model. The following code is at the bottom of routes.php file. I would like to know whether there is simpler solution for this task.
Route::bind('directslug', function($value, $route) {
$post = Post::where('slug', $value)->first();
if ($post) {
return $post;
}
$page = Page::where('slug', $value)->first();
if ($page) {
return $page;
}
throw new NotFoundHttpException;
});
Route::get('{directslug}', function(Post $post) {
return $post;
});
Route::get('{directslug}', function(Page $page) {
return $page;
});
App::missing(function($exception) {
return Response::view('error.missing', array('title' => '404 Page not Found'), 404);
});
I handle everything with route model binding , fairly similarly to your solution.
In my opinion you should keep a separate model for each route, otherwise you might end up with a post having the same slug of a page... even if I'm sure you've taken care of this. You use two different routes afterall, why should you always query for a post if someone is looking for a page?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.