I want to upload multiple images and save different filename to database.
I have an HTML code:
<input type="file" id="upload_file" name="image[]" multiple/>
and a database table:
id
image1
image2
image3
image4
image5
created_at
updated_at
Whether it can be like this?
image[]
is an array.You can store array elements in different columns this way:
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();
}
Normal way:
$image=$_POST['image'];
INSERT INTO table (image1,image2,image3...)VALUES('$image[0]','$image[1]','$image[2]...);
I believe that the correct way is to make an Image
model with a corresponding table, then you would set its relations with other models. Something like:
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();
}
}
I don't know why you are saving the pictures the way specified in the question. But if you insist, you must add new fields
id | image1 | image1_name | image2 | image2_name ...
Then in your code:
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();
}