Upload Multiple Images Via Laravel 4 - php

How to upload multiple images through laravel 4? With the codes below I get only the last image. If I select imgA, imgB, imgC, and imgD, I saved only imgD. I need imgA, imgB, imgC, and imgD.
public function store()
{
$date = new DateTime();
$timestamp = $date->format('U');
$pid = Input::get('pid');
$file = Input::file('image');
if ($file->isValid()) {
$destinationPath = public_path().'/images/';
$oriname = Str::lower(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = Input::file('image')->getClientOriginalExtension();
$fileName = $timestamp.'_'.$oriname.'.'.$extension;
Input::file('image')->move($destinationPath, $fileName);
$url = asset('images/'.$fileName);
}
$newImage = New Image;
$newImage->property_id = $pid;
$newImage->path = $url;
if ($newImage->save()){
return array('status'=>'Image saved.');
}
}

Try like this ..
$date = new DateTime();
$timestamp = $date->format('U');
$pid = Input::get('pid');
$files = Input::file('image');
foreach ($files as $file) {
if ($file->isValid()) {
$destinationPath = public_path().'/images/';
$oriname = Str::lower(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = $file->getClientOriginalExtension();
$fileName = $timestamp.'_'.$oriname.'.'.$extension;
$file->move($destinationPath, $fileName);
$url = asset('images/'.$fileName);
}
$newImage = New Image();
$newImage->property_id = $pid;
$newImage->path = $url;
if (! $newImage->save()) {
// error
}
}
Hope it will be useful for you.

Related

how to update multiple images in laravel?

i want store the images for product the product having multiple images the problem is that i want to update the images problem is images are updated but the entry never goes to database. instead it stores same entry two times.
if($request->hasfile('image')) { //here i got images
$file = $request->file('image');
$file_count= count($file); //for updating multiple images
for ($i=0; $i < $file_count; $i++) {
$imagesize = $file[$i]->getClientSize();
$imageexten = $file[$i]->getClientOriginalExtension();
$product_image_count = count($request->productimagename);
for ($i=0; $i < $product_image_count; $i++) {
if($file_count != 1) {
$new_name = $request->productimagename[$i].$i.".".$imageexten;
} else {
$new_name = $request->productimagename[$i].".".$imageexten;
}
$product_image_path ='images/frontendimage/product_image/'.$new_name;
Image::make($file[$i])->save($product_image_path);
foreach ($product->images as $key => $value) {
product_image::find($value->id)->where('product_id','=',$product->id)
->update(['image_name'=> $new_name,'image_url'=>$product_image_path,
'modified_by'=>Auth::user()->id]);
}
}
}
}
if ($request->has('unit_images'))
{
$promotion = [];
foreach ($request->file('unit_images') as $key => $file) {
$filenameWithExt = $file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = uniqid() . '.' . $extension;
$path = $file->storeAs("$directory/unit_images/$b/$unit_num", $fileNameToStore, 'public');
$this->validate($request, [
'images' => 'dimensions:min_width=250,min_height=250'
]);
$b_id = $request->building_name;
$unitimg = UnitImage::where('unit_id', '=', $unit_store_id)->get();
$new=strlen($unitimg);
if ($new!='2') {
foreach ($unitimg as $get2) {
$get2->delete();
}
$nn=New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
if ($new=='2') {
$nn = New UnitImage();
$nn->images = $path;
$nn->unit_id = $unit_store_id;
$nn->save();
}
}
}
Input Field -
<input type="file" name="images[]" class="form-control" multiple required />
Controller -
$imagesName = array();
$imagesPath = array();
if($files=$request->file('images')){
foreach (Input::file('images') as $file) {
$name = strtolower($file->getClientOriginalName());
$name = preg_replace('/\s+/', '_', $name);
$img = Image::make($file);
$path = 'your/path/'.$name;
$img->save($path);
$imagesName[] = $name;
$imagesPath[] = $path;
}
}
This will upload multiple images to your server and you will get uploaded image names from $imagesName[] and path from $imagesPath[].
Now you can use those according to your BD structure.

Image upload in Laravel

I want to upload an image much like a profile image to the project I am working with. I do not want multiple images that can be uploaded simultaneously. The previous image has to delete when a new image is uploaded.
Can anybody help me with this?
I am new to Laravel.
you can use these as reference.
This is for storing the data.
public function store(Request $request)
{
$input = $request->all();
//handle file upload
if ($request->hasFile('partner_img')) {
$fileNameWithExt = $request->file('partner_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('partner_img')->getClientOriginalExtension();
$partner_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('partner_img')->move('images/partners', $partner_img);
$input['partner_img'] = $partner_img;
} else {
$package_img = 'noimage.jpg';
}
$partner = $this->partnerRepository->create($input);
Flash::success('Partner saved successfully.');
return redirect(route('partners.index'));
}
this is for updating.
public function update($id, Request $request)
{
$input = $request->all();
$partner = $this->partnerRepository->findWithoutFail($id);
if (empty($partner)) {
Flash::error('Partner not found');
return redirect(route('partners.index'));
}
if ($request->hasFile('partner_img')) {
$fileNameWithExt = $request->file('partner_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('partner_img')->getClientOriginalExtension();
$new_partner_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('partner_img')->move('images/partners', $new_partner_img);
Storage::delete('partners/'.$partner->partner_img);
$input['partner_img']= $new_partner_img;
}
$partner = $this->partnerRepository->update($input, $id);
Flash::success('Partner updated successfully.');
return redirect(route('partners.index'));
}
I did it this way along with some other fields. Now it is solved:
public function update(Request $request)
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'file' => 'required|max:100000|mimes:doc,docx,pdf',
'email' => 'required|email',
]);
$peoples = People::find($request->id);
$peoples->Name = $request->name;
$peoples->Email = $request->email;
$peoples->Address = $request->address;
if ($request->hasFile('image')) {
if ($peoples->image) {
File::delete(public_path($peoples->image));
}
$imageName = time() . '.' . request()->image->getClientOriginalExtension();
request()->image->move(public_path('images/'), $imageName);
$peoples->image = $imageName;
}
if ($request->hasFile('file')) {
if ($peoples->File) {
File::delete(public_path($peoples->File));
}
$fileName = time() . '.' . request()->file->getClientOriginalExtension();
request()->file->move(public_path('files/'), $fileName);
$peoples->File = $fileName;
}
$peoples->update();
$peoples->save();
}

How to Replace and Delete previous files uploaded, when Edit a record in Laravel 4.2

I use laravel 4.2, because this project has been around for years. :)
Now, how can i replace and delete previous files uploaded in public
directory, when edit a record ?
Given the following Controller code ( Update Methode ) :
public function update($id)
{
$idd = Sentry::getUser()->id;
try {
$validator = Validator::make(
Input::all(),
array(
'first_name' => 'required',
'last_name' => 'required',
'eng_certificate' => 'image|mimes:png,jpeg,jpg|max:1100',
'profile_img' => 'image|mimes:png,jpeg,jpg|max:1100',
)
);
if ($validator->passes()) {
$profile = User::find($id);
$profile->first_name = Input::get('first_name');
$profile->last_name = Input::get('last_name');
if (Evidence::where('user_id', $idd)->count() == 0) {
$evidence = new Evidence;
$evidence->user_id = $idd;
$evidence->created_at = jDate::forge()->time();
} else {
$evidence = Evidence::where('user_id', $idd)->first();
$evidence->updated_at = jDate::forge()->time();
}
if (Input::hasFile('eng_certificate')) {
$image = Input::file('eng_certificate');
$destinationPath = 'uploads/evidence';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->eng_certificate = $image_filename;
$evidence->save();
}
}
if (Input::hasFile('profile_img')) {
$image = Input::file('profile_img');
$destinationPath = 'uploads/evidence/profile_img/';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->profile_img = $image_filename;
$evidence->save();
}
}
$profile->save();
return Redirect::route('cpanel.home')->with('success', 'اطلاعات پروفایل شما با موفقیت بروز گردید.');
}
else {
return Redirect::back()->withInput()->withErrors($validator->messages());
}
}
catch (LoginRequiredException $e) {
return Redirect::back()->withInput()->with('danger', $e->getMessage());
}
}
How can I fix it?
Thank you.
find out current file location
use php unlink function
https://www.w3schools.com/php/func_filesystem_unlink.asp
You can interact with the filesystem by using: Laravel Filesystem
For example:
Storage::delete('file.jpg');
See: https://laravel.com/docs/5.8/filesystem#deleting-files

Laravel : How to save multiple image file to database

I want to save multiple image files with different field in database such as product_image, feature_image, slurp_image. I used following controller method to save the image files
public function store(Request $request)
{
$product = new Product();
if($request->hasFile('product_image'))
{
$file = Input::file('product_image');
$imageName = time().'.'.$request->product_image->getClientOriginalExtension();
$product->product_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('feature_image'))
{
$file = Input::file('feature_image');
$imageName = time().'.'.$request->feature_image->getClientOriginalExtension();
$product->feature_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('slurp_image'))
{
$file = Input::file('slurp_image');
$imageName = time().'.'.$request->slurp_image->getClientOriginalExtension();
$product->slurp_image = $imageName;
$file->move('images/', $imageName);
}
// dd($product->product_image);
// dd($product->feature_image);
// dd($product->slurp_image);
$product->save();
}
when i dd() the $product->product_image,$product->feature_image, $product->slurp_image i saw different different file name , but after it stored into the database i saw same file stored into database in different different field.
anyone help to find out what could be the solution please?
When you're uploading multiple images at once you'd be passing through an array of images.
This is what my controller function has looked like when I've done this previously.
public function multiple_upload() {
// get the files
$files = Input::file('images');
// counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach ($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads'; // upload folder in public directory
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
// save into database
$extension = $file->getClientOriginalExtension();
$entry = new Uploads();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $filename;
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('upload');
} else {
return Redirect::to('upload')->withInput()->withErrors($validator);
}
}
In your example, I'd image it would be more like this
$product = new Product();
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->file('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $file)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$product->image1 = $filename[0];
$product->image2 = $filename[1];
$product->image3 = $filename[2];

Multiple Image Upload in Laravel 5.2

Finally I can upload and move the images, but now I want to create a multiple upload images on Laravel. Is that possible? Did I have to use array to make it?
Can I just modify a little bit from this code?
It's on my ProductController.php
$picture = '';
if ($request->hasFile('images')) {
$file = $request->file('images');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Thank you.
Note: My code above is from a kindhearted person on stackoverflow, thanks again ;)
At your frontend form you'll have to use your field attribute name like
name="images[]"
And your controller code would be like this.
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
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']);
}
Your input from $_POST will be coming in as an array. All you need to do is to iterate through it:
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
}
Slight modified code to upload multiple image.
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('images');
$picture = array();
if($request->hasFile('images')) :
foreach ($input as $item):
$extension = $item->getClientOriginalName();
$name = date('Ymd') . '.' . $extension;
$destinationPath = base_path() . '/uploads/images/';
$item->move($destinationPath, $name);
$arr[] = $name;
endforeach;
$picture = implode(",", $arr);
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple pictures are uploaded successfully');
return redirect('/image-upload');
}

Categories