How to upload multiple image in laravel
here is what worked best for me:
first do this in your form:
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/details">
and this for multiple selection:
<input required type="file" class="form-control" name="images[]" placeholder="address" multiple>
Now do this in your controller:
public function store(request $request) {
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
/*Insert your data*/
Detail::insert( [
'images'=> implode("|",$images),
'description' =>$input['description'],
//you can put other insertion here
]);
return redirect('redirecting page');
}
Hope this works
Multiple image upload in laravel
change input name
<input type="file" name="image[]" id="files" class="form-control">
controller
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
if ($request->hasFile('image')) {
foreach($request->file('image') as $file)
{
$image = new Listingimage();
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
}
}
return redirect()->back();
}
How to Upload Multiple Images from Multiple Browsing in Laravel?
This might not be what you are looking for but should guide you in the right direction. I see you are using vanilla JavaScript which might make things trickier. But since you are also using Laravel and Laravel ships with Vue support (at least it used to), I'll be showing you my implementation using Vue. If you know JavaScript, it shouldn't be that hard to understand as Vue is very easy.
The trick with multi file uploading is to use another array to store your files as the native FileList
object that is returned by the file input is immutable. Look at the code snippets below (I have tried to add comments to explain what I'm doing.)
You can see a working example in this pen.
<!-- @change is the Vue equivalent of onchange -->
<input @change="handleFileSelect" type="file" multiple>
<ul>
<li v-for="(photo, index) in photos" :key="`thumb-${index}`">
<img :src="photo.preview" :alt="photo.file.name">
<button @click="removePhoto(index)" type="button">Remove Photo</button>
</li>
</ul>
In the HTML section, all we have to do is to listen to changes to the file input and setup a place where we can display thumbnails for the selected images. Vue makes this very easy by using the v-for
directive to iterate over an array. The current element in the iteration is available for the li
and its child elements and we can use it to populate attributes such as the img
's src
.
export default {
data() {
return {
photos: []
}
},
methods: {
handleFileSelect(e) {
Array.from(e.target.files).forEach(file => {
// perform check here such as making sure its an image
const reader = new FileReader()
reader.onload = () => {
// push the preview result and also the file to photos array
this.photos.push({
preview: reader.result,
file
})
}
reader.readAsDataURL(file)
})
},
removePhoto(index) {
this.photos.splice(index, 1)
},
upload() {
const fd = new FormData()
this.photos.forEach((photo, index) => {
// we only want to append the actual file, excluding the preview
// so we only append the `file` attribute
fd.append(`photo-${index}`, photo.file)
})
// send the data
// for example, using axios
const uploadEndpoint = ''
axios.post(uploadEndpoint, fd, {
headers: {
'Content-Type': 'multipart/form-data' // important
}
})
}
}
}
The JavaScript part is pretty easy. What we are doing here is setting up a photos
"local state" to store our photos. We use this variable to iterate over and display thumbnails in our HTML. When a user selects images, we take the files and generate a thumbnail for them using the FileReader
object and push it to the photos
variable along with the actual file.
{
preview: 'data:image/....', // the file preview generated by the FileReader
file: File object // the actual file the user selected
}
When a user wants to unselect an image, we just splice
it from the photos
array so the photos
array will always contain photos the user wants to upload. When we come to uploading, if we are using AJAX to send the request we can just create a FormData
object and append each photo to it by iterating over the photos
variable. In a Laravel backend, these photos can then be accessed using request()->file()
. Before sending your request you have to set the proper headers though, mainly the Content-Type: multipart/form-data
.
I hope this gave you some general idea on how to proceed with this issue. If you have any questions feel free to leave them in the comments section and I'll try my best to explain more.
UPDATE: More info on working with the photos on your Laravel Backend
Once you are successfully sending the request from your front end, you can access the photos/files using Laravel's request()->file()
helper function. This will return all the files in the request in an array.
dd(request()->file());
Output will look something like:
array:3 [
"photo-0" => Illuminate\Http\UploadedFile {#221
-test: false
-originalName: "The Dark Reef Fugitive.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "/tmp"
filename: "phpjr6Cx5"
basename: "phpjr6Cx5"
pathname: "/tmp/phpjr6Cx5"
extension: ""
realPath: "/tmp/phpjr6Cx5"
aTime: 2020-03-03 08:29:19
mTime: 2020-03-03 08:29:19
cTime: 2020-03-03 08:29:19
inode: 12976169
size: 298634
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
"photo-1" => Illuminate\Http\UploadedFile {#243
-test: false
-originalName: "Nevermore.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "/tmp"
filename: "php3LNGW5"
basename: "php3LNGW5"
pathname: "/tmp/php3LNGW5"
extension: ""
realPath: "/tmp/php3LNGW5"
aTime: 2020-03-03 08:29:19
mTime: 2020-03-03 08:29:19
cTime: 2020-03-03 08:29:19
inode: 12976170
size: 322173
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
"photo-2" => Illuminate\Http\UploadedFile {#250
-test: false
-originalName: "Magnanumus.png"
-mimeType: "image/png"
-error: 0
#hashName: null
path: "/tmp"
filename: "phpJZ9El6"
basename: "phpJZ9El6"
pathname: "/tmp/phpJZ9El6"
extension: ""
realPath: "/tmp/phpJZ9El6"
aTime: 2020-03-03 08:29:19
mTime: 2020-03-03 08:29:19
cTime: 2020-03-03 08:29:19
inode: 12976172
size: 1068594
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
]
As you can see each file is an instance of Illuminate\Http\UploadedFile
. To store this file, you have a couple of options. One is to use the store
or storeAs
function on the file or just use the Storage
facade's put
or putFileAs
method. Here is an example:
$filePaths = collect(request()->file())->values()->map(function ($photo) {
return Storage::put('photos', $photo);
// OR
// return Storage::putFileAs('photos', $photo, $photo->getClientOriginalName());
// OR
// return $photo->store('photos');
// OR
// return $photo->storeAs('photos', $photo->getClientOriginalName());
});
Read the Laravel docuemntation on file storage to understand other options.
$filePaths
will be an array of paths where the photos were stored.
Adding captions or descriptions to multiple image upload in Laravel
I assume that you only want each project image to have one caption. If that's the case then the nested foreach loops are unnecessary and changing it to one foreach like this should solve the problem.
foreach ($this->projectImages as $key => $value) {
$image_name = $value->getClientOriginalName();
$value->storeAs('public/photos', $image_name);
$projectImages = new ProjectImages();
$projectImages->project_id = $project->id;
$projectImages->images = $image_name;
$projectImages->caption = $this->captions[$key];
$projectImages->save();
}
Problem in multiple image upload in laravel 8
Look like issue is due to storing array values in database fields .If you are trying to store images in comma separated then
$gallery->image_name = implode(', ',$name);
or
change
$name[] = $upload_image_name;
to
$name[]['image_name'] = $upload_image_name;
and for storing
GalleryImage::insert($name);
Related Topics
Registry Design Pattern...Good or Bad
Day of the Week to Day Number (Monday = 1, Tuesday = 2)
How to Detect the Screen Dpi Using JavaScript
Sort Array of Objects by Date Field
Using Xpath with PHP to Parse HTML
What's the Best Way to Localise a Date on Laravel
Does PHP's $_Request Method Have a Security Problem
Check If Links Are Broken in PHP
PHP Script to Delete Files Older Than 24 Hrs, Deletes All Files
Using Curl in PHP with Client Certificate and Private Key in Separate Files
Php: Whats the Total Length of a Post Global Variable
How to Find Error Log Files for PHP
Long Running Background PHP Script Blocks Other PHP Pages Until It Is Finished
Get a PHP Datetime Difference in Days, Considering Midnight as a Day Change