Uploading an image in Laravel is quite simple. Even you can upload multiple images and store them in the database. Sometimes, we require to update or remove image of any existing record. In that case, we update the generally stored image name inside the database. But what about the uploaded file in the directory? We don’t think about it. Just think about the storage, if you are storing 10 or 100 images for one record and it requires to has only one image correspondingly. Then why cannot we delete the existing image? It will save storage space. So, it is a good way to manage the storage space by removing the existing image or file of any record. Today, in this tutorial, I will gonna show you how you can remove image in Laravel 8 from the public directory.
Prerequisites
I assume you are ready for creating the Laravel 8 project with the following configurations.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
I am going to create a new project to remove image in Laravel 8.
Create Project in Laravel 8
For creating the project, I will be using the composer dependency manager. You can also use the Laravel installer. Open the terminal or command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel image-delete
The above command started the installation of Laravel 8. Let it finish the installation process.
Laravel 8 Multiple Images Upload with Validation
Create and Configure Database
For creating the database, I have used the MySQL command line. So, open the terminal and create a database by hitting the below command.
CREATE DATABASE laravel8_image;
Here, the database is created. Now, it will require to connect with the created Laravel 8 project.
So, open the root folder of the project then navigate to .env file. Now, for the database configuration, just add the below credentials. Don’t forget to add your database username and password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8_image
DB_USERNAME={{DB_USER_NAME}}
DB_PASSWORD={{DB_PASSWORD}}
Hence, after the database connection, let’s move to the functionality for uploading image first.
How to Configure PHPMailer in Laravel 8 For Sending Email
Create Model and Migration
To remove image in Laravel 8 from the public folder, we have to upload the image first. For creating model, migration, and controller, I will be using a single command.
php artisan make:model Image -mc
The above command will create a Model file inside the app/Models. Also, it will create a migration file for storing the table schema. And the last file is the controller, so here, it has created the ImageController.php file.
Dynamic Email Configuration in Laravel 8 For Sending Email
Now, after creating the above files, let’s add some fields in the migration file of the image table.
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string("image_name")->nullable();
$table->timestamps();
});
}
Here, in the above file, I have added the field name. So, after adding the above migration, let’s add the fillable fields in the model file.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
"image_name"
];
}
Lastly, we have to migrate the database file by running the migration file.
php artisan migrate
Here, the above command will migrate the table. Once, the migration is completed, let’s move ahead for image uploading and the other functionalities.
Upload and Remove Image in Laravel 8
In this post, I will just use basic functionality for uploading the image. Then, I will just list out the images and will implement the Delete functionality. This delete functionality will delete the image from the database and also it will delete image from folder. As we know, Laravel has a public folder in which the uploaded image will be saved there.
So, open the ImageController.php and add the below code there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageController extends Controller {
// ------------------- [ Index ] ----------------------
public function index() {
$images = Image::all();
return view("index", compact("images"));
}
// --------------- [ Upload Image ] -------------------
public function uploadImage(Request $request) {
$image = $request->file('image');
$imageName = time(). ".". $image->extension();
$image->move(public_path('uploads'), $imageName);
$imageStatus = Image::create([
"image_name" => $imageName
]);
if(!is_null($imageStatus)) {
return back()->with("success", "Image uploaded successfully.");
}
else {
return back()->with("failed", "Failed to upload image.");
}
}
// ---------------- [ Delete image ] ----------------
public function deleteImage(Request $request) {
$image = Image::find($request->id);
unlink("uploads/".$image->image_name);
Image::where("id", $image->id)->delete();
return back()->with("success", "Image deleted successfully.");
}
}
In the above functions, I have added the following functionalities-
- In the first function (index), I have fetched the uploaded images and returned them to the index view.
- The next function contains the code for uploading the image that is coming through the form. Here, I have uploaded the image and stored it in the images table in the database.
- The last function will delete the selected image from the folder, and also, it will delete that row from the table.
In the next step, we will have to add the routes for the above functions.
Add Route to Delete Uploaded Image
We will require to add the routes in the web.php file. Here, the route will contain the function for loading a view with the upload images. Also, the view will contain the action to add a new image and delete image.
So, firstly, open the web.php file and add the below routes there.
<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get("image", [ImageController::class, "index"])->name("image");
Route::post("upload-image", [ImageController::class, "uploadImage"])->name("upload-image");
Route::delete("delete", [ImageController::class, "deleteImage"])->name("delete");
After adding the above routes, we will have to create a view. The view will contain the data from the database. So, let’s create it.
Create a View
Open the resources/views folder and create a new blade file. Here, I created a file with the name index.blade.php. After creating the blade file, let’s add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title>Upload Image and Remove in Laravel 8 </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<style>
.table tr td {
vertical-align: middle;
}
</style>
<body>
<div class="container py-5">
<h4 class="text-center font-weight-bold">Image Upload and Remove</h4>
<div class="row py-2">
<div class="col-xl-6">
@if(Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>{{Session::get('success')}}
</div>
@elseif(Session::get('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>{{Session::get('failed')}}
</div>
@endif
</div>
</div>
<div class="card">
<div class="card-header">
<div class="card-title-wrapper d-flex justify-content-between">
<h5 class="card-title font-weight-bold">Images</h5>
<a href="javascript:void(0)" data-toggle="modal" data-target="#imageModal" class="btn btn-sm btn-primary pt-2 add-new-btn">Add New </a>
</div>
</div>
{{-- table --}}
<div class="card-body">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@forelse ($images as $image)
<tr>
<td>{{$image->id}}</td>
<td><img src="{{url('uploads/',$image->image_name)}}" class="img-fluid" style="height:100px"></td>
<td class="d-flex"><a href="javascript:void(0)" data-toggle="modal" data-target="#imageModal" data-id="{{$image->id}}" data-image="{{$image->image_name}}" class="btn btn-sm btn-success btn-edit">Edit</a>
<form action="{{route('delete')}}" method="post">
@csrf
@method('DELETE')
<input type="hidden" name="id" value="{{$image->id}}"/>
<button type="submit" class="btn btn-sm btn-danger ml-2">Delete</button>
</form>
</td>
</tr>
@empty
<h4 class="text-danger text-center">No image found.</h4>
@endforelse
</tbody>
</table>
</div>
</div> {{-- card ends --}}
{{-- modal --}}
<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<form action="{{route('upload-image')}}" class="w-100" method="post" enctype="multipart/form-data">
@csrf
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title font-weight-bold">Upload Image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-xl-12 m-auto">
<input type="hidden" name="imageId" id="imageId">
<input type="hidden" name="oldImage" id="oldImage">
<div class="form-group file-input">
<input type="file" name="image" class="form-control">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(".add-new-btn").click(function() {
$("#imageId").val("");
$("#oldImage").val("");
$("div .old-img").remove();
});
$(".btn-edit").click(function() {
var id = $(this).attr("data-id");
var imageName = $(this).attr("data-image");
$("#imageId").val(id);
$("#oldImage").val(imageName);
if(imageName !== undefined) {
$(".modal-title").text("Update Image");
$(".file-input").after("<div class='form-group old-img'><img src='uploads/"+imageName+"' style='height:100px;'></div>");
}
});
});
</script>
</body>
</html>
In the above snippet, I have used a basic table design using the bootstrap. Also, I populated the images which are coming from the database using the controller. For extracting the image data, I used Laravel for else loop. This loop will check the array has the data then it will extract, otherwise, you can set any specific message if there is no data.
Check Result by Uploading and Deleting Image
Save and run the application to see the result. Open the route in the browser. Here, at the first time there is no any uploaded image in the folder and no row in the database.
So, upload an image by clicking on the Add New button. Here, it will open the modal.
Choose the image and upload it. Here, I have selected an image and uploaded it.
If the image is uploaded successfully, you will get a success response as showing below.
So, the image is uploaded successfully. I can show you in the folder. Here, the image is uploaded.
Delete Image From Folder in Laravel
Here, you can see the Delete action in the image view. When you will click on that action, it will delete the image from the folder. Also, it will delete that particular row from the table.
So, let’s check it.
After deleting the image, it is deleted from the folder and from the database.
Conclusion
Finally, we uploaded and removed image from the folder in Laravel 8. PHP provides the unlink() function to remove any existing image or file from the folder. It will detach the selected file from the folder. So, I hope you will find it very easy to implement in your project.
quyle says
thanks for your article. It helps Laravel starter like me a lot…
have a nice day!