pandeydip
pandeydip

Reputation: 33

How to change request method in Yii2 custom URL rules from GET to POST and others?

I am trying to work in RESTfull web services in Yii2 using default controller. But the problem I faced is, I cannot send POST request with parameters. Below is my code:

Url Manager rule in web.php

'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => array(
            ['pattern' => 'api/v1/auth/payment/<id:\d+>', 'route' => 'api/v1/auth/payment'],
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ),
    ],

AuthController.php file this is inside controller/api/v1/

namespace app\controllers\api\v1;

use app\controllers\api\v1\components\ApiFunctions;
use Yii;
use yii\web\Controller;


class AuthController extends Controller
{
    public function actionPayment()
    {
        $id = Yii::$app->getRequest()->getQueryParam('id');
        json_encode($id);
    }

}

But when I send GET request to http://{url}//api/v1/auth/payment/5 I get response as 5. But I want to get that result when sending POST or any other methods.

So how can I achieve that?

Upvotes: 3

Views: 4280

Answers (2)

tnchalise
tnchalise

Reputation: 1583

Let me show you how i solve it for my application.

A simple application structure i have constructed for basic application setup was.

------ app

------modules

----------api

-------------modules

----------------v1

-------------------controllers

-------------------models

-------------------etc

You can simply go through the application setup first.

Then define verb filtering in every controller or sort it out by defining in a common class, as i have done here.

Then with the same rule you have defined in urlManager, you will able be to get the request query parameter.

Hope this helps.

Upvotes: 2

vitalik_74
vitalik_74

Reputation: 4611

Use

'POST <controller:\w+>s' => '<controller>/create',

See more http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html

More example from documentation

[
    'dashboard' => 'site/index',

    'POST <controller:\w+>s' => '<controller>/create',
    '<controller:\w+>s' => '<controller>/index',

    'PUT <controller:\w+>/<id:\d+>'    => '<controller>/update',
    'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete',
    '<controller:\w+>/<id:\d+>'        => '<controller>/view',
];

Upvotes: 1

Related Questions