Uploading multiple files in Laravel 5 - laravel

I have been trying to upload multiple files in Laravel using the code below but it only uploads a single image. Please help
$files = $request->file('file');
foreach ($files as $file){
$filename = time().'.'.$file->getClientOriginalExtension();
$location = public_path('uploads/'.$filename);
$file->move(public_path().'/uploads/', $filename);
$filename_arr = [];
array_push($filename_arr, $filename);
$filename = json_encode($filename_arr);
$upload->filename = $filename;
}

Blade: As you want to upload multiple file append [] to the input type name property with multiple as below :
<input type="file" name="file[]" multiple>
Logic:
if($request->hasFile('file'))
{
$files = $request->file('file');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$file->move(public_path().'/uploads, $filename);
}
}

Related

LARAVEL - MULTIPLE FILE UPLOAD DOESNT WORK AND RETRIEVING

When I click on submit, it's only storing last selected file where it suppose to store all the images and how to retrieve those files? Any suggestion or example? Do I need to have different attributes for multiple files?
Controller
if (is_array($request->carEvidence)) {
foreach ($request->carEvidence as $key => $file) {
$destinationPath = public_path('image/');
$profileImage = $key . "-" . date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move($destinationPath, $profileImage);
$post['carEvidence'] = "$profileImage";
}
}
Views
<input type="file" name="carEvidence[]" multiple>
MYSQL
https://ibb.co/9sPLw8C
File Input
https://ibb.co/VHkxRwc
you are passing multiple files in array, so you have to use loop to retrieve all the files in controller.. something like
if (is_array($request->carEvidence))
{
foreach ($request->carEvidence as $key => $file) {
$destinationPath = public_path('image/');
$profileImage = $key."-".date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move($destinationPath, $profileImage);
// code to save in your db table
}
}

Laravel upload multiple files

I'm building a gallery with multiple files functionality.
So far I'm having two issues, but let's paste my code first.
Controller:
public function store(Request $request)
{
$gallery = new GalleryImage();
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
}
}
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
return back()->with('success_message','Images has been uploaded!');
}
View blade:
<form action="{{ route('gallery-images.store') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<input type="hidden" name="gallery_id" value="{{ $gallery->id }}">
<input type="file" name="image[]" id="id_imageGallery" class="form-control" multiple="multiple" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
My first issue when I have my code like this and upload three files, it's successfully storing the files into /uploads/temp directory, but in my database I can see there's only one image uploaded, instead of three.
My second issue is when I change my code and use the commented part (because I want to store those three images into Storage):
$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
I'm getting this error:
Call to a member function storeAs() on array
How can I upload those multiple images into the Storage folder and record them all into the database?
-- EDIT --
I've solved my first issue!
I've simply put the save method and other details inside the loop. I've should have thought about this before :)
Here's my updated code:
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}
Now only thing to do is how to store them into File Storage, instead of the public_path and avoid that error:
Call to a member function storeAs() on array
I've finally solved the issues and I'm posting it, so it may be useful for some.
Here's my code:
public function store(Request $request)
{
if($request->hasFile('image')) {
foreach($request->image as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery = new GalleryImage();
$gallery->image = $image->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','The images have been uploaded!');
}
Try to implement using the following code, it will give uploaded files url in serialized format
public static function upload_file($file){
$file_name = time();
$file_name .= rand();
$file_name = sha1($file_name);
if ($file) {
$ext = $file->getClientOriginalExtension();
$file->move(public_path() . "/uploads", $file_name . "." . $ext);
$local_url = $file_name . "." . $ext;
$s3_url = url('/').'/uploads/'.$local_url;
return $s3_url;
}
return "";
}
public static function upload_multiple_files($files){
if(is_array($files)){
$return_array = array();
foreach ($files as $file){
if(!empty($file)){
$return_array[] = self::upload_file($file);
}else{
$return_array[] = '';
}
}
return serialize($return_array);
}else{
return NULL;
}
}
//I have updated and commented your code. Try it, It should work.
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
// laravel auto manages unique name and extension of file.
$gallery->image = $image->store('gallery-images', 'public');
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}

Cannot use object of type Illuminate\Http\UploadedFile as array

I try to send attachement files but i get
Cannot use object of type Illuminate\Http\UploadedFile as array
I use laravel 5.4
Someone know why i'm getting this error ?
( I don't upload the file into a directory, i just want to send the file who was requested on my controller )
Hope someone could help , best regards :)
Here my controller :
public function postSendMassive(Request $request){
$files = $request->file('uploads');
$emails = Structure::where('type_structure_id', 4)->pluck('adresse_email_structure');
$subject = $request->subject;
$bodyMessage = $request->texte;
foreach($files as $file) {
$files[] = [
'file' => $file->getRealPath(),
'options' => [
'mime' => $file->getClientMimeType(),
'as' => $file->getClientOriginalName()
],
];
}
Mail::to('test#gmaIL.com')->send(new MassiveEmail($subject , $bodyMessage , $files));
return back()->with('status', "Email envoyé");
}
here my build mail :
public function build()
{
$subject = $this->subject;
$bodyMessage = $this->bodyMessage;
$files = $this->files;
$email = $this->markdown('email.MassiveMail',compact('bodyMessage'))
->subject($subject.'-'.'FFRXIII Licences & Compétitions');
foreach($this->files as $file) {
$email->attach($file['file'],$file['options']);
}
return $email;
}
This is because $request->file('uploads') returns an object and you're trying iterate over it with foreach
If you want to upload multiple files, make sure you're doing something like this:
<input type="file" name="uploads[]" multiple />
And iterate over uploaded files:
foreach ($request->uploads as $file)
This works!
if($request->hasFile('files')){
foreach ($request->files as $file) {
//get file name with extenstion
$fileNameWithExt = $file->getClientOriginalName();
//get just filename
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $file->getClientOriginalExtension();
//file to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload to store
$path = $file->storeAs('${your_storage_path}', $fileNameToStore);
}
}

laravel using switch cases to upload files

how can i upload inputs files in different folders i need to use switch cases to make every input file in different folder and did this code but when i execute it nothing happen i want know where problem
my view
{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}
my controler
$model = new Files($request->all());
switch ($model) {
case "file1":
if ($request->hasFile('file1')) {
$file = $request->file('file1');
$destinationPath = public_path() . '/file1';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file1'] = $filename;
$model -> file1 = $filename;
$model->save();
}
break;
case "file2":
if ($request->hasFile('file2')) {
$file = $request->file('file2');
$destinationPath = public_path() . '/file2';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file2'] = $filename;
$model->file2 = $filename;
$model->save();
}
break;
case "file3":
if ($request->hasFile('file3')) {
$file = $request->file('file3');
$destinationPath = public_path() . '/file3';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file3'] = $filename;
$model->file3 = $filename;
$model->save();
}
break;
case "file4":
if ($request->hasFile('file4')) {
$file = $request->file('file4');
$destinationPath = public_path() . '/file4';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file4'] = $filename;
$model->file4 = $filename;
$model->save();
}
break;
}
Ummm yeah I had do something like that, but I do it use foreach loop and if after that.
And here's my sample code, I hope it can help :-D
$requests = $request->all();
$model = new File;
foreach ($requests as $key => $val) {
if ($key == 'file1' && !empty($val)) {
$destinationPath = public_path() . '/file1';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
if ($key == 'file2' && !empty($val)) {
$destinationPath = public_path() . '/file2';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
// And do it again as much as you need :D
}
Here you go, I hope it can help you pals :D

i m saving the multiple images at a single time with differnt ID in database in Laravel

and it is saved but the issue is all the images have different auto
increment ids in database i want to save the images with the same ids
which is save at the same time,kindly guide me.
****strong text** the code is below;**
$field = Input::file('image');
$location = public_path('uploads/');
foreach ($field as $k => $fd) {
$filename = str_random(2).'-' . time() . "." . $fd->getClientOriginalExtension();
$fd->move($location , $filename);
$product->image = $filename;
}
$user->save();
I think bellow code helps you..
You can try.
$picture = '';
if ($request->hasFile('image')) {
$files = $request->file('image');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}

Resources