Delete Image with category Delete - laravel

I have this function that deletes the row but does not delete the image from the folder. I thought this would work but it doesn't. Can someone help change this code so I can delete the image from the folder on delete?
Thanks
public function PermDelete($id)
{
$category = Category::find($id);
File::delete(public_path('images/categories/'. $category->cat_image));
$delete = Category::onlyTrashed()->findOrFail($id)->forceDelete();
return redirect()->back()->with('success','Category has been permanently deleted successfully!');
}

instead of use
File::delete(public_path('images/categories/'. $category->cat_image));
you can simply use the PHP function unlink to delete
unlink(public_path('images/categories/'. $category->cat_image));
or you can debug with the below code
$path = public_path('images/categories/'. $category->cat_image);
if(\File::exists($path)){
\File::delete($path);
}else{
dd('File does not exists.');
}

Related

How to delete photo from project's public folder before updating data in lumen/laravel?

I am trying to delete photo from my projects public folder before updating another photo. My code looks like-
if(File::exist( $employee->avatar)){
//$employee->avatar looks /uploads/avatars/1646546082.jpg and it exist in folder
File::delete($employee->avatar);
}
This is not working in my case. If I comment these code then another photo updated without deleting perfectly. How can I solve the issue!
try php unlink function
$path = public_path()."/pictures/".$from_database->image_name;
unlink($path);
This is the code which i use in update profile picture you can do this exactly like this
$data=Auth::user();
if($request->hasFile('image')){
$image = $request->file('image');
$filename = 'merchant_'.time().'.'.$image->extension();
$location = 'asset/profile/' . $filename;
Image::make($image)->save($location);
$path = './asset/profile/';
File::delete($path.$data->image);
$in['image'] = $filename;
$data->fill($in)->save();
}

Replace Old image with new image in laravel

CONTROLLER
public function updateproduct(Request $request, $id)
{
// dd($request->all());
$request->validate([
'name'=>'required',
'description'=>'required',
'price'=>'required|numeric',
'quantity'=>'required|numeric',
]);
$product = Product::where('id', $id)->first();
if(is_null($product)) {
$product = new Product();
}
$product->name=$request->name;
$product->description=$request->description;
$product->price=$request->price;
$product->quantity=$request->quantity;
if($request->hasfile('images')){
$existingimages = Image::where(['product_id'=> $product->id, 'source'=> 1])->get();
if($existingimages->count() > 0)
foreach($existingimages as $existingimage) {
$filename = public_path().'files/'.$existingimage->name;
if(file_exists($filename)){
unlink($filename);
$existingimage->delete();
}
}
foreach($request->file('images') as $file){
$name = rand(1,9999).'.'.$file->getClientOriginalName().$file->getClientOriginalExtension();
if($file->move(public_path().'/files/', $name)){
$updateImage = Image::firstWhere('product_id', $product->id);
$updateImage->images = $name;
$updateImage->source = 1;
$updateImage->save();
}
}
}
Please check updated question. Request you to correct me if I wrong. Right now it only updates 1 image and other images remains same. please help me with this.
Your code is somewhat confusing, I'm afraid.
Your request appears to allow for multiple images to be uploaded. Here :
if(file_exists($imagePath)){
unlink($imagePath);
}
you look like you're trying to delete any images that already exist, but when you store upload images you're assigning them a random name (which Laravel can already handle for you, by the way, so there's no need to do it yourself) so you're unlikely to be actually deleting them because there'll likely be no file at that location anyway.
Nowhere does your code actually delete any existing images from the database. Essentially what you want to do is :
If the upload has images, retrieve all the existing images for that product.
Delete the physical files for those existing images.
Delete the database entries for those existing images.
Upload your new images and save their details to the database.
Translating that into code means :
if($request->hasfile('images')){
// Delete any existing image files and database entries.
$existingimages = Image::where('product_id', $product->id)->get();
if($existingimages->count() > 0)
foreach($existingimages as $existingimage) {
$filename = public_path().'files/'.$existingimage->name;
unlink($filename);
$existingimage->delete();
}
}
// Carry on with your upload
}
It adds new images because you are using the Image::create method. If I understood correctly, you want to modify the images of your products in the image table.
Try to modify your code like :
$updateImage = Image::firstWhere('product_id', $product->id);
$updateImage->images = $name;
$updateImage->source = 1;
$updateImage->save();

Laravel Voyager BREAD Image Edit and Delete Issue

I have ran into a problem with image upload using voyager BREAD System. If I delete or update an image using BREAD the old image not replaced or deleted. It is still in the storage directory. I was using latest version of voyager with laravel 5.5. Is there any solution to this problem? Thank you in advance.
There is no public function deleteBreadImages($data, $rows) {...} anymore in Laravel Voyager 1.2 class file vendor/tcg/voyager/src/http/controllers/VoyagerBreadController.php
After two days of googling same issue I figured out the Hard Solution...
in my case image field name is img and model name is Company
code is executed while the Model BREAD is updating
Works on Voyager 1.2
Hope it helps ))
use Storage;
class Company extends Model
{
public static function boot()
{
parent::boot();
static::updating(function($model)
{
// Check if Old File Exists
$oldFileExists = Storage::disk('public')->exists($model->original['img']);
// If Old File Exists DELETE it, else Continue Adding New Image
if($oldFileExists)
{
//Get File Extension:: .jpg .png .gif
$fileExt = substr(strrchr($model->original['img'], "."), 0);
//If File is not .GIF
if($fileExt != '.gif'){
// Delete Old Non-GIF Image
Storage::disk('public')->delete($model->original['img']);
}
// Find .gif , -static.gif Old Images And Delete
else{
// filename-static.gif
$staticOld = str_replace($fileExt,"-static".$fileExt,$model->original['img']);
// Delete Old Image.gif
Storage::disk('public')->delete($model->original['img']);
// Delete Old Image-static .gif if Exists
if($staticOld) Storage::disk('public')->delete($staticOld);
}
}
});
}
}
Hey please check below file in your project's vendor/tcg/voyager/src/http/controllers/VoyagerBreadController.php directory
and check for this
public function deleteBreadImages($data, $rows) {...}
function at line number 403.
in this function find $this->deleteFileIfExists($data->{$row->field}); make it un-comment and check.
may i hope this helps you

Unlink, image into directory

I have a file called delete.php inside where I created this code:
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = #$_GET['id'];
$img = #$_GET['h_image'];
if(file_exists($img)){
unlink('../images/'.$img);
}
// delete the entry
$result = DB::table('questions')
->where('id', '=', $id)
->delete();
// redirect back to the view page
header("Location: index.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: index.php");
}
The content is properly deleted from the database, but unfortunately I can not erase the image corresponding to the directory "images".
I tried with unlink, but by mistake.
How can I do?
Obviously the image must match the content to be deleted.
Thanks guys, I hope for your help.
I did so, but always from tabase but not delete the image from the directory:
Maybe I'm wrong path of the image? The GET?
// get id value
$id = #$_GET['id'];
$path = #$_GET['img'];
if(file_exists($path))
unlink("images/".$path);

Can't write image data to path in laravel

I am having the same error as this guy is :
Another thread
basically the error i have is uploading the image to the specific path, my code is as follows :
public function postCreate() {
$validator = Validator::make(Input::all() , Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products'.$filename);
$product->image = 'public/img/products'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message' , 'Product created');
}
return Redirect::to('admin/products/index')->with('message' , 'something went wrong')
->withErrors($validator)->withInput();
}
I was just trying to follow a tutorial on laravel e-commerce web application.
I guess the problem is that i don't have write permisson in my directory , how do i add write permission in my directory. I.E. the public folder, I googled a few places , but i don't understand what is it that i have to edit ?
I.E the htaccesss file or can i make write changes on the cmd ? also how do i check what weather a directory is write protected .
PS. i am using windows . i am attaching a screenshot of the error .
Thank you.
You might want to change the dateformat since windows doesn't allow colons in filenames:
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
And you also might want to add a trailing slash to your path so it doesn't concatenate the filename to the folder path:
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products'.$filename);
Generally this error occurs when you do not yet have the directory that will store the image inside the public directory. Sometimes it can be a permission issue.
Does you img directory exists in your public directory?
To fix this, follow the steps:
Use this snippet:
$relPath = 'img/'; //your path inside public directory
if (!file_exists(public_path($relPath))) { //Verify if the directory exists
mkdir(public_path($relPath), 666, true); //create it if do not exists
}
Or manually create the img directory in public
2.Then you can save your image:
Image::make($image)->resize(468, 249)->save(public_path('img/products'.$filename)); //save you image
$product->image = 'img/products'.$filename; //note
$product->save();
**NOTE: We do not need to specify the public directory in the path because we are using a relative path. The img directory will be created inside public directory.
Along with this, you need to make sure the folder path exists and which has right permissions set.
$relPath = 'img/product/';
if (!file_exists(public_path($relPath))) {
mkdir(public_path($relPath), 777, true);
}
Where $relPath is the path relative to public directory.
This requirement is however windows specific. In linux, folder directory will be created if it does not exist.
I also recommend all of you to check if $path exists. Like Jose Seie use native PHP check, I recommend you to thought about build-in helpers.
This can be achieved with File Facade helper:
File::exists($imagePath) or File::makeDirectory($imagePath, 777, true);
Advice you to use Laravel built-in functions, classes & helpers to improve the performance of your application!
well , i made the correction that john suggested and then made the following corrections :
I replaced the below code :
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products'.$filename);
with :
$path = public_path('img/products/'.$filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
problem solved , i don't know why public_path works , but never mind .

Resources