URL routing rules in Yii2

Volatil3 picture Volatil3 · May 21, 2015 · Viewed 11.5k times · Source

Coming from background of Laravel and Rails I am finding quite a difficulty to figure out how Yii2 rules work.

I am looking for following URL patterns:

  • /articles/
  • /articles/view/
  • /articles/1/my-pretty-article

ArticlesController is defined like:

<?php

namespace app\controllers;

class ArticlesController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionView()
    {
        return $this->render('index');
    }

}

So far I have tried:

'urlManager' => [
            'showScriptName' => false,
            'enablePrettyUrl' => true,
            'rules' =>
                [
                    'articles/view' => 'article/view'
                ],
        ],

I am more interested to redirect my pattern to controller@method.

Answer

Valery Viktorovsky picture Valery Viktorovsky · May 21, 2015

It's possible to use <id> param:

 'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        '<controller:\w+>/<id:\d+>/<slug:\w+>' => '<controller>/view',
    ],
],

And your articles controller:

<?php

namespace app\controllers;

class ArticlesController extends \yii\web\Controller
{
    public function actionView()
    {
        $id = (int) Yii::$app->request->get('id');

        return $this->render('index');
    }
}