如何使用laravel 5.1上传多个图像并将其名称存储在数据库中? [英] How to upload multiple images and store their name in database with laravel 5.1?

查看:36
本文介绍了如何使用laravel 5.1上传多个图像并将其名称存储在数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个表单,供用户上传多个图像,并将上传的图像移动到上传"文件夹并将其名称存储在数据库中.这是我的代码

I have created a form for users can upload multiple images,and move uploaded images to 'Upload' folder and store their names in database. This is my code

public function multiple_upload() {
    $multiupload = new Multiupload();
// getting all of the post data
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
  $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
  $validator = Validator::make(array('file'=> $file), $rules);
  if($validator->passes()){
    $destinationPath = 'uploads';
    $filename = $file->getClientOriginalName();
    $upload_success = $file->move($destinationPath, $filename);
    $uploadcount ++;
    $multiupload->fileimage = $filename;
    $multiupload->save();
  }
}
if($uploadcount == $file_count){
  Session::flash('success', 'Upload successfully'); 
  return Redirect::to('/');
} 
else {
  return Redirect::to('/')->withInput()->withErrors($validator);
}

}

上传后,所有图像均成功移至上传"文件夹,但在数据库中仅存储一个图像名称.那么如何将所有图像名称存储在数据库中呢? 请帮助我,谢谢您的帮助.

After upload all images successfully move to 'Uploads' folder but, in database it store only one image name. So how to store all images name in database? Please help me and thanks you for help.

推荐答案

如@ edrzej.kurylo所述

As @edrzej.kurylo said

您必须将以下行添加到foreach($files as $file) {

You have to add the below line to inside of foreach($files as $file) {

$multiupload = new Multiupload();

因为要一次又一次地重复使用相同的Multiupload功能.每次循环运行时,您都必须重新初始化模型.

Because you are reusing the same Multiupload function again and again. You have to re initialize the Model for every time the loop runs.

这篇关于如何使用laravel 5.1上传多个图像并将其名称存储在数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆