IN tutorial we will be implementing the four basic CRUD actions in a RESTful manner. The RESTful actions boil down to three main HTTP request types—GET, POST, and DELETE. We’ll implement each one for our users.

The first method we need to implement is our loadModel() method. This method will be loaded in our User model and will throw the appropriate errors if something goes wrong:

private function loadModel($id=NULL)
    if ($id == NULL)
        throw new CHttpException(400, 'Missing ID');

    $model = User::model()->findByPk($id);

    if ($model == NULL)
        throw new CHttpException(400, 'User not found');

    return $model;

Deleting users

The first method that we’ll implement is our DELETE method. Remember that, for each method, we’ll be hitting a single endpoint, /api/user/index , with different HTTP request types:

  1. The first change that we need to make is to our accessRules. We want only administrators to have the ability to delete a user. We’ll do this by setting up an expression that checks whether the user is an admin:
        'actions' => array('indexDelete'),
        'expression' => '$user!=NULL&&$user->role->id==2'
  2. Then, we’ll implement the delete action. We want to make sure that users are not able to delete themselves:
    public function actionIndexDelete($id=NULL)
        if ($id == $this->user->id)
             return $this->returnError(401, 'You cannot delete yourself', null);
         return $this->loadModel($id)->delete();

    Sending a DELETE request to /api/user/index/id/<user_id> will now delete a user with the given ID.