URL routing rules in Yii2

11,476

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');
    }
}
Share:
11,476
Volatil3
Author by

Volatil3

A developer and a wannabe entrepreneur. More than 10 years of development experience on different platforms; Windows,Linux, Mac,Desktop/Web/Mobile. You can read further about me on my home site

Updated on June 04, 2022

Comments

  • Volatil3
    Volatil3 almost 2 years

    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.