phpyii2yii-url-manager

use blog name and id in url using yii2


I need to use blogname and id on the url on Yii2 like this is my url now :- http://localhost/html/demo/web/site/blog/blogdetail?id=39

I want to modify this link to :-

http://localhost/html/demo/web/site/blog/blogdetail/39/Did-Facebook-Skew-The-2016

This is my blog name "Did-Facebook-Skew-The-2016"

for this i am using that code:- web.php file.

   'rules' => array(
                     'blog/blogdetail/<id:\w+>/<name:\w+>'=>'site/blog/blogdetail/id/<id>/name/<name>/',
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),

and in view this is my link:-

 <a href="<?php echo Yii::$app->urlManager->createUrl([$blogid.'/'.$model->title]); ?>">

Solution

  •  <a href="<?php echo Yii::$app->urlManager->createUrl(['site/blog/blogdetail', 'id'=>$blogid, 'name'=>$model->title]); ?>">
    

    As a sidenote, you can change the route from

    'blog/blogdetail/<id:\w+>/<name:\w+>'=>'site/blog/blogdetail/id/<id>/name/<name>/',
    

    to

    'blog/blogdetail/<id:\w+>/<name:\w+>'=>'site/blog/blogdetail/',

    Named params (id and name in this case) are automatically passed to the action.

    EDIT: If you have problem with the params type you can change

    <name:\w+>
    

    with

    <name:[\w-]+>
    

    Your slug (Did-Facebook-Skew-The-2016) should now match.