Saturday, August 7, 2010

How to use SEO urls in CakePHP without the ID

CakePHP offers massive support to create SEO friendly URLs on the fly. You can create SEO-friendly-urls without an ID value to refer to specific post id. It works like a charm like many other Cake MAGIC!

I'll refer to the post table.
1. Create a field called 'slug' (must be UNIQUE and NOT NULL) in the post table.

2. Download and use sluggable behavior to create post slug! Follow instructions step-by-step. It works perfectly.

3. Define routing rules in config/router.php file to display SEO friendly urls.




               'controller' => 'posts',

               'action' => 'view'



               'slug' => '[-a-z0-9]+',

               'pass' => array('slug')



4. In posts_controller.php view() function modify query,

function view($slug = null)
        if (empty($slug))
                // redirect ...
         $data = $this->Post->findBySlug($slug) ; 

You you should be able to access urls of the form:

Hope it helps someone.

1 comment:

kvn promo said...

Nice article to sharing this post.........