Deleting the image from the database and server
We would like to have a delete feature in our script, using which we will delete the image both from the database and from its uploaded folder. This process is quite easy with Laravel.
- First, we need to create a new route for the action. To do this, open
app/routes.php
and add the following lines://This route is to delete the image with given ID Route::get('delete/{id}', array ('as'=>'delete_image','uses'=> '[email protected]')) ->where('id', '[0-9]+');
- Now, we need to define the controller method
getDelete($id)
insideimageController
. To do this, openapp/http/controllers/imageController.php
and add the following code above the last curly bracket (}
):public function getDelete($id) { //Let's first find the image $image = image::find($id); //If there's an image, we will continue to the deletingprocess if($image) { //First, let's delete the images from FTP
File::delete(Config::get('image.upload_folder').'/'.$image->image); File::delete(Config::get('image.thumb_folder').'/'.$image->image);
//Now let's delete the value from database $image->delete(); //Let's return to the main page with a success message return Redirect::to('/')->with('success','image deleted successfully'); } else { //image not found, so we will redirect to the indexpage with an error message flash data. return Redirect::to('/')->with('error','No image with given ID found'); } }
Let’s understand the code:
- First, we look at our database, and if we have an image with a given ID already with the
find()
method of Eloquent ORM, we will store it with a variable called$image
. - If the value of the
$image
is not false, there is an image matching the image in our database. Then, we delete the file with thedelete()
method of the File class. Alternatively, you can also use the unlink() method of raw PHP. - After the files are deleted from the file server, we delete the image’s information row from the database. To do this, we are using the
delete()
method of Eloquent ORM. - If everything goes smoothly, we should redirect back to the main page with a success message saying the image is deleted successfully.
Note
In practical application, you should have a backend interface for such actions.
Wrapping up
In this tutorial , we’ve created a simple image sharing website with Laravel’s built-in functions. We’ve learned how to validate our forms, how to work with files and check their MIME types, and set custom configuration values. We’ve learned more about database methods both with Fluent and Eloquent ORM. Also, for image processing, we’ve installed a third-party library from packagist.org using Composer and learned how to update them. We’ve also listed images with the page navigation feature and learned to delete files from the server.
hope you will like it :)
- First, we look at our database, and if we have an image with a given ID already with the
Comments