The Tutorial on how to upload an image to Yii2 model

This has been covered but I feel it’s not easy enough.

Here are the steps

  1. Add Image upload to your Model

    use yii\web\UploadedFile;

  2. Add a new variable to hold the uploaded image.

    public $eventImage;

  3. Add a rule to handle this variable.
    I prefer to add my image after I have created a row, this makes it easier should you have a failure to upload something.

    [['eventImage'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],

  4. Define logic in your Controller to save the file to a path of your choice

     public function actionUpload($id)
    

    {
    $model = $this->findModel($id);

     if (Yii::$app->request->isPost) {
         $model->eventImage = UploadedFile::getInstance($model, 'eventImage');
         if ($model->upload()) {
             return $this->redirect(['view', 'id' => $model->id]);
    
         }
     }
    
     return $this->render('upload', ['model' => $model]);
    

    }

  • Watch out for naming of variables issue. This is the biggest problem. $this->eventImage must be the variable pointing to it. if something does not work, its probably the naming.
  1. Create a upload path function in the model. Use a seperate model function so that you can test it separately. Do not forget to create the folder for it

    public function upload() {
    
    if (true) {
    	$path = $this->uploadPath() . $this->id . "." .$this->eventImage->extension;
        $this->eventImage->saveAs($path);
    	$this->image = $this->id . "." .$this->eventImage->extension;
    	$this->save();
        return true;
    } else {
        return false;
    }		
    

    }

    public function uploadPath() {
    return Url::to('@web/uploads/events');
    

    }