@rollin
To delete an image using AJAX in Laravel, follow these steps:
1
|
Route::delete('images/{id}', 'ImageController@deleteImage')->name('images.delete'); |
1 2 3 4 5 6 7 8 9 10 11 12 |
public function deleteImage($id) { $image = Image::findOrFail($id); // Delete the image from the storage Storage::delete($image->path); // Delete the image from the database $image->delete(); return response()->json(['message' => 'Image deleted successfully']); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function deleteImage(id) { if (confirm('Are you sure you want to delete this image?')) { $.ajax({ url: '/images/' + id, type: 'DELETE', success: function(response) { console.log(response.message); // Refresh the page or update the image gallery }, error: function(xhr, status, error) { console.error(error); } }); } } |
1
|
<button onclick="deleteImage({{ $image->id }})">Delete Image</button> |
Make sure to replace {{ $image->id }}
with the actual ID of the image you want to delete.
By following these steps, you can delete an image using AJAX in Laravel.