Dat Tran Dat Tran - 2 months ago 9
Ajax Question

File isn't deleted when code is in a specific order

I ran into the problem that when I try to delete a record from database using

->delete()
and my code stopped after successfully deleted the record.

This code doesn't execute the
Storage::delete($image)


public function productImageDelete(Request $request){
if($request->ajax()):
$image_id = Input::get('image-id');
$image = Input::get('image');
try {
$image = Image::findOrFail($image_id);
$image->delete();
Storage::delete($image); //This doesn't execute at all
return "success";
} catch ( \Illuminate\Database\QueryException $e) {
return $e;
}
endif;
}


However when I placed
Storage::delete($image)
before
$image->delete();
the code works.

public function productImageDelete(Request $request){
if($request->ajax()):
$image_id = Input::get('image-id');
$image = Input::get('image');
try {
Storage::delete($image); //This executes first
$image = Image::findOrFail($image_id);
$image->delete();
return "success";
} catch ( \Illuminate\Database\QueryException $e) {
return $e;
}
endif;
}

Answer

You need to take a look at the details. You're creating two variables named $image and that's your issue.

On the first case, you're calling Storage::delete($image); where $image is an object and on the second case, you're calling the same method but in that case $image is a Input::get('image').

If you simply rename the variable of Input::get('image') to, say $imageParam = Input::get('image') and execute Storage::delete($imageParam);, it should work on both cases.

The bottomline is: never use the same variable name, as it will led to such unnecessary confusions.

Comments