Laravel 5.5 - multiple images upload - php

I have this function in my controller:
use File;
use Image; //image intervention library
...
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
endforeach;
endif;
return 'success';
}
which only save the last image if I upload multiple.
and I tried:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
$file->save($path);
endforeach;
endif;
return ''success;
}
which throw me error:
Method save does not exist.
I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?
What is the best way for multiple images upload in laravel?
Update
After reading #kunal's answer, I managed to solve the issue by adding a unique number for the file name:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
$count = 0;//<-- add a counter
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
$count ++;//<-- increase the value
endforeach;
endif;
return 'success';
}

May be you are looking for this kind of stuff:-
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$folderpath = 'images'.'/';
$file->move($folderpath , $fileName);
}
}
<input type="file" id="gallery" name="files[]" multiple />

I am thinking u may missed this part
<input type="file" id="gallery" name="file[]" />
note the file[] it must be array otherwise it will only save the last image if upload multiple image
If u did ur html part correct, then use like this,
foreach ($file as $photo) {
$path = Storage::putFile('foldername', $photo);
}

try this code:
$files= Input::file('image');
$destinationPath= 'images';
$images=array();
foreach($files as $file){
$fullname= $file->getClientOriginalName();
$hashname = $fullname;
$upload_success =$file->move($destinationPath, $hashname);
$images[]=$fullname;
$has= implode(",",$images);
}
$modelname= new Modelname;
$modelname->image_attachment = $has;
$modelname->save();
and yout html page:
<input type="file" id="image" name="image[]" />

It is not that complicated.
As of larval 5.8 you can do this:
collect($request->images)->each(function ($image) {
return $image->store('images', 'public');
});
It puts images in images folder of public disk.

Related

How can i upload multiple files into a CELL?

I tried uploading multiple files into my database but I keep getting just one file, Am using laravel 5.5 all files show on my file directory path but store only one file into my database. Here is my code
my view
<label for="image">{{ __(' image') }}</label>
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
my route
Route::post('/people/employees/test/{id}', 'EmplController#test');
my controller
if($request->hasfile('image')){
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
i inserted image here->$employee->image = $filename;
$employee->save();
}
}
Make an array, and implode it before insert to table, like :
$files = []; // an empty array
foreach($a as $b) {
$files[] = $b->name; // insert name to array
}
$files = implode(",", $files); // insert $files into your table
So you need to change on your code :
if($request->hasfile('image')){
$files = []; // make an array
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename; // insert to array
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'), $filename);
}
$files = implode(",", $files); // insert $files into your table
}

how can i keep saved files in a cell everytime i upload a new file? am using laravel 5.5

I created a user table with employee's details, and in my image column I have a file uploaded in its cell. How can I keep old file every time I upload a new file.
my view.blade
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
<th> {{$employee['image']}}</th>
my controller
if($request->hasfile('image')){
$files = [];
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
}
$files = implode("</br>;", $files);
}
$employee->image = $files;
$employee->save();
Just change one line :
$employee->image = $files;
to,
$employee->image = $employee->image . $files;

Laravel upload file in different folder

public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
move_uploaded_file($_FILES['filename']['tmp_name'], public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}
How can I upload the same image into different folders.
I have tried the above code and it doesn't work in the other folder.
You can't run move_uploaded_file twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
// Note that here, we are copying the destination of your moved file.
// If you try with the origin file, it won't work for the same reason.
copy($filepath.$filename, public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}
use Illuminate\Support\Facades\Storage;
public function upload(Request $request){
$filename = time() . '.jpg';
$filepath = public_path('uploads/newfolder/');
$file = $request->file( "filename" );
Storage::putFileAs( $filepath, $file, $filename );
echo Storage::url( 'uploads/newfolder/'.$filename );
}
You should try this:
Try with copy upload folder image to new folder like:
use Illuminate\Support\Facades\File;
$imgUpload = File::copy(public_path().'/uploads/'. $filename, public_path().'/newfolder/'. $filename);

same hash multiple images

Well, I want to create only one hash for multiple files i upload so all those files will have the same hash so i can load all of them at once using that hash, but the problem is that in the store function hash changes for every file and i want it to stay the same for that upload
public function store(Request $request)
{
$picture = '';
$hash = substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 8);
if ($request->hasFile('images'))
{
$files = $request->file('images');
foreach($files as $file) {
$image = new Upload();
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') .'.'. $extension;
$destinationPath = base_path() . '/public/storage';
$file->move($destinationPath, $picture);
$image->hash = $hash;
$image->file_name = $picture;
$image->path = '/storage/'.$picture;
$image->save($request->all());
return redirect('/a/'.$hash);
}
}
}
You can generate hash and place it in upload form hidden field. After upload just read $_POST['hash'] instead of generating it in store().

move 'tmp' directory not working when uploading image in laravel 5.4

When uploading my image it is saved to D:\xampp\tmp\phpD0E0.tmp directory. But I want to save it in public/uploads/banner. Anyone please help me. Here is my code:
BannersController.php
public function store(Request $request)
{
$requestData = $request->all();
if ($request->hasFile('banner_image')) {
foreach($request['banner_image'] as $file){
$uploadPath = public_path('/uploads/banner');
$extension = $file->getClientOriginalExtension();
$fileName = rand(11111, 99999) . '.' . $extension;
$file->move($uploadPath, $fileName);
$requestData['banner_image'] = $fileName;
}
}
Banner::create($requestData);
Session::flash('flash_message', 'Banner added!');
return redirect('Banner/banners');
}
Can you please revert that path to 'root' => storage_path('app/public')
and just try with change line:
$extension = $file->getClientOriginalExtension();
$fileName = rand(11111, 99999) . '.' . $extension;
with this:
$fileName = rand(11111, 99999) . '.' . $file->getClientOriginalName();
Hope this helps you.

Categories