Hello,
I am facing some problems with uploading multiple pictures.
Problem:
Sometimes...
- when I want to upload 3 pictures, it will upload only 2 of the 3 and name one equally to one of the 2 uploaded, so it has the same name within the DB.
- when I want to upload 2 pictures, it will store 2 records for only one picture within the DB.
- it stores/uploads 2 pictures I selected, correctly.
When I dd:
foreach ($request->images as $image) {
dd($request->images);
}
it correctly returns (without any deviation)
array:3 [▼
0 => UploadedFile {#370 ▶}
1 => UploadedFile {#371 ▶}
2 => UploadedFile {#372 ▶}
]
Controller:
$this->validate($request, [
'business_image'=> 'max:2048',
]);
foreach ($request->images as $image) {
$business = Auth::user();
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('uploads/'. $filename );
$image = Image::make($image->getRealPath());
$image->resize(812, null, function ($constraint){$constraint->aspectRatio();})->save($location);
$pictures[] = new Picture(['business_image' => $filename]);
}
$business->pictures()->saveMany($pictures);
Picture.php
public function business(){
return $this->belongsTo(Business::class);
}
Business.php
public function pictures(){
return $this->hasMany(Picture::class);
}
Pictures Table:
Schema :: create ('pictures', function(Blueprint $table){
$table->increments('id');
$table->unsignedInteger('business_id'); //
$table->string('business_image')->default('default.jpg');
$table->timestamps();
});
Problem Assumptions:
a) Could $filename = time() . '.' . $image->getClientOriginalExtension(); be a problem, because the filename is stored by the upload time? When I add mt_rand() it still faces at least problem 1)
b) When I use 3 pictures with different extensions, it sometimes stores 2 different pictures with the same filename(time string) but different extension.
c) Maybe one image can't get through the size validation, but I also tested it with 2 pictures and sometimes they uploaded, sometimes they didn't.
Any suggestions?