L
L
Light7772015-12-01 16:13:33
Yii
Light777, 2015-12-01 16:13:33

How to update a file in yii2?

I want to do something like a blog. Generated the usual CRUD. I screwed up the ability to add an image to the post, but the problem arose in Update. I can't overwrite the image
. The post id and photo are saved in the database (for example: link/post-id.jpg)
When updating, I just want to change the image itself in the folder so that it is overwritten. So that the old one is deleted and the new one is preserved
Please help
Below is the function of updating the post, in which I wanted to first delete and overwrite again, but it didn’t work out ...

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $file = $this->findModel($id)->photo; // 'images/'.$file (physical path)

            if (file_exists($file)) {
                unlink($this->findModel($id)->photo);
                $this->findModel($id)->delete();

                return $this->redirect(['view', 'id' => $model->post_id]);
            } else {
                return $this->render('update', [ 'model' => $model, ]);
            }
        }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question