So I am doing multiple file uploadin in yii2 and I am stuck when only one image is saving in database also in directory i get only one image
below is my controller code
public function actionMultiple(){
$model = new Media;
$model->post_id = '2';
if (Yii::$app->request->ispost) {
$model->media = UploadedFile::getInstances($model, 'media');
if ($model->media) {
foreach ($model->media as $value) {
$model = new Media;
$model->post_id = '2';
$BasePath = Yii::$app->basePath.'/../images/post_images';
$filename = time().'-'.$value->baseName.'.'.$value->extension;
$model->media = $filename;
if ($model->save()) {
$value->saveAs($BasePath.$filename);
return array('status' => true, 'message' => 'Image Saved');
} else {
return array('status' => true, 'message' => 'Image Not Saved');
}
}
}
}
return array('status' => true, 'data' => $model);
}
And this is my model code
<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "media".
*
* @property int $id
* @property int $post_id
* @property string $media
* @property string $created_at
*
* @property Post $post
*/
class Media extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'media';
}
public function behaviors()
{
// TimestampBehavior also provides a method named touch() that allows you to assign the current timestamp to the specified attribute(s) and save them to the database. For example,
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => false,
'value' => function() { return date('d-M-Y'); },
]
];
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['post_id', 'media'], 'required'],
[['post_id'], 'integer'],
[['media'], 'file', 'maxFiles' => 10],
[['created_at'], 'string', 'max' => 25],
[['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['post_id' => 'id']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'post_id' => 'Post ID',
'media' => 'Media',
'created_at' => 'Created At',
];
}
/**
* Gets query for [[Post]].
*
* @return \yii\db\ActiveQuery
*/
public function getPost()
{
return $this->hasOne(Post::className(), ['id' => 'post_id']);
}
}