How to delete image with ajax in laravel?

Member

by rollin , in category: PHP Frameworks , 4 months ago

How to delete image with ajax in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 4 months ago

@rollin 

To delete an image using AJAX in Laravel, follow these steps:

  1. Add a route in your web.php file to handle the deletion of the image.
1
Route::delete('images/{id}', 'ImageController@deleteImage')->name('images.delete');


  1. Create a method in your ImageController to handle the deletion of the image.
 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. Create a JavaScript function to make an AJAX request to delete the image.
 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. In your view file (e.g., gallery.blade.php), add a button or link that triggers the deleteImage function.
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.

  1. Test the functionality by clicking the "Delete Image" button and verifying that the image is deleted successfully.


By following these steps, you can delete an image using AJAX in Laravel.