0

It gives me the list of all users when I run this url "api/web/v1/users" using get method in Yii2 in its default rest setup.

I have a column is_active in the users table, so I only want the list of all active users "where is_active=1", my question is that how I can pass my custom conditions to get rest data?

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62
Mohd Shahid
  • 1,538
  • 2
  • 33
  • 66

4 Answers4

2

This questions contains all the code you need for a general REST query/search implementation in Yii2: Yii2 REST query

Your search can be done calling api/web/v1/users/search?is_active=1

Community
  • 1
  • 1
Fory
  • 405
  • 4
  • 12
1

add this to your REST controller

public function actions()
{
    // Overriding action
    $actions['index']['prepareDataProvider'] = function($action) 
    {
        return new \yii\data\ActiveDataProvider([
           'query' => \app\models\User::find()->where(['is_active' => 1]),

        ]);
    };

    return $actions;
}
0

You can achieve this by overriding users action or creating new action in your REST controller:

public function actionActiveUsers(){
    return User::find()->where(['active' => 1])->all();
}

Now, you can get active users via user/activeUsers URL.

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62
  • Yes, this solution is creating a new action that I don't want, I just want to use same url "api/web/v1/users" to get the desired result. – Mohd Shahid Nov 12 '14 at 09:47
  • So just override it and rename `actionActiveUsers()` to `actionUsers()` – Ali MasudianPour Nov 12 '14 at 09:54
  • I tried actionUsers but it is not overriding the default action, I tried actionIndex also since it is inside "UserController" but it is also not working. – Mohd Shahid Nov 12 '14 at 10:08
0

i have done it same task for REST APIs using ActiveDataProvider.

Comment/Disable the line of the UserController public $modelClass = 'app\model\user';

create new action i.e., actionIndex() //--- Controller action

public function actionIndex(){

$query = (new yii\db\Query())
->from('user')
->where('ia_active=:rec',[
  ':rec'=>1
]);

$dataProvider = new yii\data\ActiveDataProvider([
            'query' => $query,
        ]);

return $dataProvider;
}

Note: add url-rule in web.php (urlManager) //---web.php

'urlManager' => [
  enablePrettyUrl' => true,
  'rules' = [
    //--- other rules
    'GET,HEAD users' => 'v1/users/index',
  ]
]

try it.