Yii2 :: URL with many parameters

There are many cases when you need to get variable number of parameters via URL. For example one may want URL such as http://mkchowdhury.com/product/male/jeans to lead to ProductController: :actionCategory where it’s expected to get an array containing male and jeans.

1   Get  Ready

First of all, we need to enable pretty URLs.  In the application config file (frontend/config/main.php and if using advance template then also backend/config/main.php) add the following:

$config =  [
// …
‘components’ =>  [
II …
‘urlManager’ =>’showScriptName’ =>  false,

‘enablePrettyUrl’ =>  true,
‘rules’ => require ‘urls.php’,
    ],
],

Note that we’re including separate file instead of listing rules directly.  It is helpful when application grows large.

Now in frontend/config/urls.php and frontend/config/urls.php add the following content:

<?php

return [
‘pattern’ =>  products/<categories:.*>’,
‘route’ =>  ‘product/category’,
‘encodeParams’ =>  false,
   ],
] ;

?>

2 Create ProductController

namespace app\controllers;

use yii\web\Controller;

class ProductController extends Controller
{
   public function actionCategory($categories)
   {
     $params = explode(‘/’, $categories);
     print_r($params);
   }
}

That’s it. Now you can try http://mkchowdhury.com/products/male/jeans. What you’ll get is
Array ( [0] => male [1] => jeans)