How to change default controller and action in Yii 2.0

To change default controller and action in Yii 2.0 put these two single line codes into correct location:

Change Default Controller:

Each application has a default controller specified via the [[yii\base\Application::defaultRoute]] property. When a request does not specify a route, the route specified by this property will be used. For [[yii\web\Application|Web applications]], its value is site, while for [[yii\console\Application|console applications]], it is help.

Therefore, if a URL is http://yourdomain.com or http://yourdomain.com/index.php, it means the site controller will handle the request. To change this behaviour, change the default controller with the application configuration file which is web.php in config folder of your Yii 2.0 application:

So your application configuration will look somewhat like:

Change Default Action:

An action method is a public method whose name starts with the word action. The return value of an action method represents the response data to be sent to end users. Each controller has a default action specified via the [[yii\base\Controller::defaultAction]] property. When a route contains the controller ID only, it implies that the default action of the specified controller is requested which is by default set as index. If you want to change the default value, simply override this property in the controller class, like the following:

So in this way you can easily change default controller and action in Yii 2.0.

You Might Interested In

2 COMMENTS

    1. Amit Sonkhiya says:

      hi @mayank

      you need to set it in backend/config/main.php

      $config = [

      ‘components’ => [

      ],
      ‘params’ => $params,
      ‘defaultRoute’ => ‘user/index’,
      ];

      Reply

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.