Use case:
- I have data which has both an ID and a ROUTE
- I have a list of links and a router which use the ID so that, if the title or route ever changes, the links will always point to the same content.
- I would like the ROUTE to be displayed in the URL instead of the ID when the user goes to the page for usability and SEO purposes.
Currently, I am using a redirect for this and I doubt that’s the proper way to handle it.
public function show($slug)
{
$list = array(
// blog data goes in here
};
// when we go to the blog post page, we loop through the blog post data
foreach ($list as $post) {
// if the slug from our url is equal to the ID
if ($slug == $post['id']){
// redirect to the user-friendly route instead
$route = '/blog/' . $post['route'];
return $this->redirect($route);
}
// if this is the user-friendly, route, then render the page
if ($slug == $post['route']) {
$title = $post['title'];
$content = $post['content'];
}
}
// hello/show.html.twig is the twig template I'm currently using to render single pages
return $this->render('hello/show.html.twig', [
'title' => $title,
'content' => $content,
]);
}
This technically works, but I really don’t think it’s the actual correct method. Is there a better way of using two routes for the same view and giving preferential treatment to one route over another somewhere between the link click and the page render?
2
Answers
If you use Symfony, just type your route in routing.yml file.
Any controller action must have one render, currently you don’t use framework.
Read more about this in the doc. Instead redirection you can call action inside an action.
https://symfony.com/doc/current/components/routing.html#load-routes-from-a-file
Simply create a method in your repository called ‘findOneByIdOrSlug’ and build a query passing the value that comes from the URI to a where clause with an or. Make sure to limit the result to one and handle the exceptions properly.
Then, call that method from the controller and that should do.
Cannot provide code because I’m on my phone right now.