How to handle update on image upload - laravel

recently i'm trying to practice with laravel 5.5 and create simple upload and update image
here is my controller on store
$input = $request->all();
$this->validate($request, [
'photo' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$photo_name = date('YmdHis'). ".$ext";
$photoName = time().'.'.$request->photo->getClientOriginalExtension();
$request->photo->move(public_path('photo-upload'), $photoName);
$upload_path = public_path('photo-upload');
$input['photo'] = $photoName;
}
}
controller update
if ($request->hasFile('photo')) {
// delete the old/previous one
$exist = Storage::disk('photo')->exists($student->photo);
if (isset($student->photo) && $exist) {
$delete = Storage::disk('photo')->delete($siswa->photo);
}
// upload new one
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
$photoName = time().'.'.$request->foto->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$upload_path = 'photo-upload';
$request->file('photo')->move($upload_path, $phptpName);
$input['photo'] = $iphotoName;
}
}
the store method works perfectly, it uploaded image to the right folder then update the databse
the problem is on the update, it update the database but it didn't upload the image to the photo-upload folder
Any suggestion?
Thanks

Related

Updating an image in laravel does not save to DB, only saves when adding new record

I have the form of a service where a name, description, and photo is required. When adding a new service the form works fine, everything is saved in the database.
Problem is when I want to change the photo and upload a new one its not working.
**Here is my controller method **, for both adding and updating service
public function post(ServiceRequest $request, Service $service)
{
$service = Service::firstOrNew(['id' => $request->get('id')]);
$service->id = $request->get('id');
$service->name = $request->get('name');
$service->description = $request->get('description');
$image = $request->file('photo')->store('services/');
$service->photo = $image;
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$name = time() . $service->name . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $name);
}
if ($request->has('photo')) {
$image = $request->file('photo');
}
$service->save();
Alert::success('Service Saved');
return redirect()->back();
// dd($service);
}
I need some assistance with updating the image and removing an old one that was added on update record.

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

I am trying to upload multiple images in laravel and facing issues as the same image is uploaded each time?

The problem is that my loop only running and uploading the same first pic each time rather than uploading each other in a row one after one!
Here is my code of the form
{!! Form::file('photos[]', ['roles' => 'form', 'class' => 'form-control-file','multiple' => true]) !!}
Here is my code of the controller
$files=$request->file('photos');
foreach ($files as $file) {
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$file->getClientOriginalExtension();
$insert->Save();
$uid = $insert->id;
$file->move($destinationPath,$imageName);
$image = array(
'youth_fashion_images_img' => $imageName
);
Images::where('youth_fashion_images_id',$uid)->update($image);
}
return redirect('adminpanel/viewimages');
Try this code :
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$image->getClientOriginalExtension();
$image->move($destinationPath,$imageName);
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$insert->youth_fashion_images_img = $imageName;
$insert->Save();
}
}
You should try this code.
if($request->hasfile('photos')) {
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$name = 'uploads/products/'.time().'.'.$image->getClientOriginalName();
$image->move($destinationPath, $name);
$data[] = $name;
}
}
$insert= new Images;
$insert->youth_fashion_images_img = json_encode($data);
$insert->save();
json_encode to insert the multiple image names in one row.
So add $name in array $data[] = $name;.
I hope this will helps.

How to upload multiple images and store their name in database with laravel 5.1?

I have created a form for users can upload multiple images,and move uploaded images to 'Upload' folder and store their names in database. This is my code
public function multiple_upload() {
$multiupload = new Multiupload();
// getting all of the post data
$files = Input::file('images');
// Making 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';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
$multiupload->fileimage = $filename;
$multiupload->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/');
}
else {
return Redirect::to('/')->withInput()->withErrors($validator);
}
}
After upload all images successfully move to 'Uploads' folder but, in database it store only one image name. So how to store all images name in database?
Please help me and thanks you for help.
The reason is that you are reusing the same Multiupload instance in your loop and just overwriting the saved name with the name of next file. You should be creating a new Multiupload instance for every file that gets uploaded.
As #edrzej.kurylo said
You have to add the below line to inside of foreach($files as $file) {
$multiupload = new Multiupload();
Because you are reusing the same Multiupload function again and again. You have to re initialize the Model for every time the loop runs.
You should move your $multiupload = new Multiupload(); into the foreach loop.
foreach($files as $file) {
$multiupload = new Multiupload();
}
I would use for loop in this manner:
if($request->hasFile('images'){
$files = $request->file('images');
for($i=0; $i<count($files); $i++){
$img = new SampleImage();
$name = rand().'.'.$files[$i]->getClientOriginalExtension();
$files[$i]->move('uploads/samples/',$name);
$img->image_name = $name;
$img->save();
}
}

Upload image on laravel

add an image I can not load because it creates a new folder outside the public folder
$input = Input::all();
$polje = array('naslov' => 'required');
$provjera = Validator::make($input, $polje);
if($provjera->passes()){
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('file')->move(base_path().'/images/vijesti', $filename);
$vijest = new Vijesti();
$vijest->naslov = $input['naslov'];
$vijest->slika = $uploadSuccess;
$vijest->tekst = $input['tekst'];
$vijest->tag = $input['tag'];
$vijest->kategorija_id = Input::get('kategorija_id');
$vijest->save();
return Redirect::to('admin/vijesti/dodaj')->withInput()->with('ok', 'Vijest je uspjesno dodata.');
}else {
return Redirect::to('admin/vijesti/dodaj')->with('no', 'Greska: morate pokusati ponovo, polje naslov i slika su obavezna polja.');
}
You are using the wrong function. Use public_path() instead of base_path().
$uploadSuccess = Input::file('file')->move(public_path().'/images/vijesti', $filename);
Hope that helps :)

Resources