I want to delete images that I store in server,
I store images like this
$image1 = $postData['img']['0']->store('public');
$Add->Img1 = str_replace('public/', '', $image1 );
images save in public/storage folder
I display images like this
<img src="{{ asset('/storage/'.$add->Img1)}}">
so I need to delete this image using a tag like this
<a href="{{route('deleteImg',[app()->getLocale(),'id'=>$add->Img1]) }}" class="btn">Remove</a>
this is my route
Route::get('/deleteImg/{id}', 'AlladdsController@DeleteImg')->name('deleteImg');
this is my controller for delete images
public function DeleteImg (Request $request, alladds $alladds)
{
$img= request('id');
if(Storage::delete('/public'.'/'.$img)) {
return 'file is deleted';
}
else {
return 'file is not deleted';
}
return redirect()->back();
}
but this code is not working, what I want to do correct this code
Your route is injecting the id into the method DeleteImg()
, but you have a different field catching the injected id.
This routing:
Route::get('/deleteImg/{id}', 'AlladdsController@DeleteImg')->name('deleteImg');
pushes id into the method as the argument after $request
.
I don't know what alladds
is, and it doesn't seem to be used, so I suggest following Laravel convention and re-write the method input like so:
// Note lower case to match route method and std.
public function deleteImg (Request $request, $img){ ... }
This will inject whatever you are sending into the route right into the method. This will fix the mismatch error (if that was even an error -- not sure as you didn't say what the exact issue was).
Also - note you are calling the asset from storage
directory and then trying to delete the image from public
- these are two different places, and may well be the cause of the error - perhaps one of these locations is incorrect and thus you are trying to delete (or call) from an area where it doesn't exist.