URL routing rules in Yii2

12.1k views Asked by At

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.

1

There are 1 answers

0
Valery Viktorovsky On BEST ANSWER

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');
    }
}