Hello there. Basically I have the following problem:
I’m trying to implement a multiple images file upload system and save them to the DB. With my current code all the images get uploaded to the folder but only the last image gets saved to the DB.
Avatar.php -> The Model
<?php
namespace frontend\models;
use yii\web\UploadedFile ;
use Yii;
class Avatar extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'avatar';
}
public function rules()
{
return [
[['name', 'image'], 'required'],
[['name'], 'string'],
[['image'], 'file', 'extensions'=>'jpg,jpeg,png', 'maxFiles' => 5],
];
}
} // End
AvatarController.php
<?php
namespace frontend\controllers;
use frontend\models\Avatar ;
use Yii ;
use yii\web\UploadedFile ;
class AvatarController extends \yii\web\Controller
{
public function actionIndex()
{
$avatar = Avatar::find()->all() ;
return $this->render('index', ['avatar' => $avatar]) ;
}
public function actionCreate()
{
$avatar = new Avatar() ;
if ($avatar->load(Yii::$app->request->post())) {
$images = UploadedFile::getInstances($avatar, 'image') ;
foreach($images as $image) {
$image->saveAs('uploads/' .$image->baseName . '.' .$image->extension) ;
}
$avatar->image = $image->baseName . '.' .$image->extension ;
if ($avatar->save()) {
return $this->redirect('@app/views/avatar/index') ;
}
}
return $this->render('create', [
'avatar' => $avatar,
]);
}
} // End of the controller class
create.php -> The create form file
<?php
use yii\widgets\ActiveForm ;
use frontend\models\Avatar ;
use yii\helpers\Html ;
use yii\helpers\Url ;
?>
<?php $form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'] //
]) ; ?>
<?= $form->field($avatar, 'name') ?>
<?= $form->field($avatar, 'image[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>