Image Upload by overriding model’s parent save method

Override the parent save() method by declaring the following method in the model class Product.php. Here we have taken the example of uploading a product image and save its path to the database.

// this method will be used in create and update product

public function save($runValidation = true, $attributeNames = null)
    {

        //'imageFile' is an instance of UploadedFile class, whereas 'image' is an attribute of 'Product' class. So imageFile will contain the actual file and image will store its path.

        if ($this->imageFile) {
            $this->image = '/products/' . Yii::$app->security->generateRandomString() . '/' . $this->imageFile->name;
        }

        $transaction = Yii::$app->db->beginTransaction();
      
        // save the image path along with other model properties to the database
        $ok = parent::save($runValidation, $attributeNames);

        // if saved successfully and image is provided from the frontend
        // image file could be empty in case of 'Update Product'

        if ($ok && $this->imageFile) {
            $fullPath = Yii::getAlias('@frontend/web/storage' . $this->image);
            $dir = dirname($fullPath);
            if (!FileHelper::createDirectory($dir) | !$this->imageFile->saveAs($fullPath)) {
                
                // if directory could not be created OR file could not be uploaded
                $transaction->rollBack();

                return false;
            }
        }

        $transaction->commit();

        return $ok;
    }

Running low on budget? Get the best Shared hosting at an Affordable Rate!