title: How to create a file upload REST API controller for Yii2
body: <p>I am using Ionic framework for mobile app development. The Yii2 API code below can be used for file upload, but it doesn't work. It shows the following errors:</p>
  <blockquote>
  <p>i) Undefined offset: 0.</p>
  <p>ii) yii\db\BaseActiveRecord-&gt;save()</p>
  </blockquote>
  <pre><code>public function actionNew() {
      $model = new Apiprofile();
      $userid = $_REQUEST['user_id'];
      $photo = $_FILES['photo'];
      $model-&gt;user_id = $userid;
      $model-&gt;photo = $photo;
      $name = $model-&gt;user_id;
      $model-&gt;file = UploadedFile::getInstance($model, 'photo');
  
      if($model-&gt;file) {
          $model-&gt;file-&gt;saveAs('uploads/photos/'.$name.'.'.$model-&gt;file-&gt;extension);
          $model-&gt;photo = $name.'.'.$model-&gt;file-&gt;extension;
          $model-&gt;save();
      }
  
      $name = $model-&gt;user_id;
  
      if($model-&gt;save()) {
          echo json_encode(array('status'=&gt;1,'data'=&gt;$model-&gt;attributes),JSON_PRETTY_PRINT);
      } else {
          echo json_encode(array('status'=&gt;0,'error_code'=&gt;400,'errors'=&gt;$model-&gt;errors),JSON_PRETTY_PRINT);
      }
  }
  </code></pre>