How to use seo urls in cakephp without the id?

by genevieve_boehm , in category: SEO , 8 months ago

How to use seo urls in cakephp without the id?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by aniyah , 8 months ago

@genevieve_boehm 

To use SEO-friendly URLs in CakePHP without the ID, follow these steps:


Step 1: Enable mod_rewrite Ensure that mod_rewrite is enabled on your server. This can usually be done by uncommenting the line in your Apache configuration file.


Step 2: Enable CakePHP's routing Make sure that CakePHP's routing is enabled in your CakePHP application's configuration file (config/routes.php). The default setting should be:

1
$routes->fallbacks(DashedRoute::class);


This allows CakePHP to automatically generate and parse SEO-friendly URLs.


Step 3: Configure routes In the same configuration file (config/routes.php), you can add custom route configurations to define how your SEO-friendly URLs should be generated and handled.


For example, if you want to use the article title as part of the URL instead of the ID, you can add a route like this:

1
$routes->connect('/articles/:slug', ['controller' => 'Articles', 'action' => 'view'], ['pass' => ['slug']]);


This route configuration specifies that the URL pattern "/articles/:slug" should be mapped to the "view" action of the "Articles" controller. The "slug" parameter will be passed to the action.


Step 4: Update controller actions In your controller's action that handles the SEO-friendly URL, you need to fetch the data based on the passed parameter (e.g., "slug") instead of the ID.


For example, in the "ArticlesController" view action:

1
2
3
4
5
public function view($slug)
{
    $article = $this->Articles->findBySlug($slug)->firstOrFail();
    $this->set(compact('article'));
}


Step 5: Update link generation When generating links to your SEO-friendly URLs, you can use CakePHP's "HtmlHelper" functions.


For example, to generate a link to the "view" action of the "Articles" controller with the article's slug as the parameter:

1
echo $this->Html->link($article->title, ['controller' => 'Articles', 'action' => 'view', $article->slug]);


By following these steps, your CakePHP application should generate and handle SEO-friendly URLs without relying on the ID in the URL.