2016-09-28 121 views
-1

我想上傳多個圖像並保存不同的文件名到數據庫。laravel - 多重上傳並保存不同的文件名到數據庫

我有一個HTML代碼:

<input type="file" id="upload_file" name="image[]" multiple/> 

和數據庫表:

id 
image1 
image2 
image3 
image4 
image5 
created_at 
updated_at 

它是否能這樣嗎?

+1

什麼是你需要幫助的具體問題?是的,你可以上傳5張圖片並將他們的名字保存在數據庫中。 –

+0

如果你用不同的id將它們分成不同的記錄會更好嗎?像ID,文件名,圖像(BLOB?),創建時間,更新時間 – Jigs

回答

0

image[]是array.You可以用這種方式存儲數組元素在不同的列:

public function store(Request $request) 
{ 
    $model=new Model(); 
    $model->image1=$request->image[0]; 
    $model->image2=$request->image[1]; 
    $model->image3=$request->image[2]; 
    ... 
    $model->save(); 
} 

正常方式:

$image=$_POST['image']; 
INSERT INTO table (image1,image2,image3...)VALUES('$image[0]','$image[1]','$image[2]...); 
0

我認爲,正確的做法是讓一個Image模型一個對應的表格,那麼你可以設置它與其他模型的關係。例如:

public function store(Request $request) 
{ 
    $model = new RelatedModel(); // This is a related model example 

    $images = $request->file("image.*"); 
    foreach($images as $uploadedImage) 
    { 
     $path = $uploadedImage->store('path/images', 'local'); // disk can be null, it will then use the default disk in filesystems.php 
     $image = new Image(); 
     // A way you want to use to give the image a name 
     $image->name = $this->generateName(); 
     $image->path = $path; 
     // Where relatedModel is the method on Image model defining a belongsTo relation for example with RelatedModel 
     $image->relatedModel()->associate($model); 
     $image->save(); 
    } 

} 

我不知道你爲什麼要按照問題中指定的方式保存圖片。但是,如果你堅持,你必須在你的代碼添加新字段

id | image1 | image1_name | image2 | image2_name ... 

然後:

public function store(Request $request) 
{ 
    $model=new Model(); 

    // This is a function you would make to generate a different name than the path 
    $model->image1_name = $this->generateName(); 
    $model->image1 = $request->file("image.0");->store('path/images', 'local'); 
    $model->image2_name = $this->generateName(); 
    $model->image2 = $request->file("image.1");->store('path/images', 'local'); 
    // ...etc. 

    $model->save(); 
} 
相關問題