Yii 2.0: How to get SEO friendly URL using Model and new getUrl() function

1 follower

We all need SEO friendly URLs for our projects. its not always good to call route with params so we can generalise it for all models using a common function.

Following the general convention of model and control sharing common name, we can use this code to get seo friendly URL.

public function getControllerID() {
        $modelClass = get_class ( $this );
        $pos = strrpos ( $modelClass, '\\' );
        $class = substr ( $modelClass, $pos + 1 );
        return Inflector::camel2id ( $class );
    }
    public function getUrl($action = 'view', $id = null) {
        $params = [ 
                $this->getControllerID () . '/' . $action 
        ];
        if ($id != null)
            $params ['id'] = $id;
        else
            $params ['id'] = $this->id;
        // add the title parameter to the URL
        $params ['title'] = ( string ) $this;
        // absolute url
        return Yii::$app->getUrlManager ()->createAbsoluteUrl ( $params, true );
    }

In code code where ever you need to url to a model , you just call $model->url or $model->getUrl('view').

You may have to additionally update urlManager in config with rules for pretty url.

'<controller:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/view',
                                '<controller:[A-Za-z-]+>/<id:\d+>' => '<controller>/view',
                                '<controller:post>/<id:\d+>/<title>' => 'blog/view',
                                '<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/<action>',
                                '<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>' => '<controller>/<action>',

you will get url like this.

http://localhost/link/650/need-a-professional-developer

Be the first person to leave a comment

Please to leave your comment.

Write new article
  • Written by: shiv
  • Category: How-tos
  • Yii Version: 2.0
  • Votes: +1
  • Viewed: 1,346 times
  • Created on: Sep 21, 2017
  • Last updated: Sep 21, 2017
  • Tags: beautiful url