Building a Basic Image Uploader in Laravel: A Step-by-Step Guide
Image is one of the most essential element of a website because it makes the visual connections with the users. Handling images efficiently when building websites is important for speed and performance. As a framework of php, in laravel you can opt for many ways to upload and store images in the server efficiently. You can convert the whole image to binary format and store it as BLOB (Binary Large Object). But also alternatively, we can just move the image to a specific location in our application and save the path to retrieve the image when needed, which is a smart approach. In this article, we will see a basic example of uploading images in Laravel efficiently.
Lets start with setting up model and database
Assume, we have already installed a fresh laravel application in our local.
First, lets create a model and migration to upload our images
php artisan make:model Image -m
A new migration file will be generated for the model. Lets update the migration file generated for Image model as below:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('images');
}
}
Then please run the migration:
php artisan migrate
Setup the routes
We will add 3 routes to perform separate actions. Lets see the code first in web.php:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageUploadController;
Route::get('/upload', [ImageUploadController::class, 'index']);
Route::post('/upload', [ImageUploadController::class, 'uploadImage']);
Route::delete('/upload/{id}', [ImageUploadController::class, 'deleteImage']);
So here, the Get route will show the image uploading form and the Post route will handle actions after the form submission.
And the Delete route will be used for deleting the image from our server.
Setting up controller
Now here is the action part. In the index method, as mentioned in Get route, we show the form. uploadImage method from Post route, will hold the logic for uploading images and deleteImage for image deletion.
Please update ImageUploadController like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
class ImageUploadController extends Controller
{
public function index()
{
$images = Image::all();
return view('upload', compact('images'));
}
public function uploadImage(Request $request)
{
// Validate the image
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// Handle the image upload
if ($request->file('image')) {
$image = $request->file('image');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $imageName);
// Save the image name to the database
$imageRecord = Image::create(['name' => $imageName]);
return back()->with('success', 'Image uploaded successfully')->with('image', $imageRecord);
}
return back()->with('error', 'Image upload failed');
}
public function deleteImage($id)
{
$image = Image::findOrFail($id);
$imagePath = public_path('images') . '/' . $image->name;
if (file_exists($imagePath)) {
unlink($imagePath);
}
$image->delete();
return back()->with('success', 'Image deleted successfully');
}
}
Now lets have some clarification for what we are doing with code above.
uploadImage: In the uploadImage method, first we are validating image as a required one, should be image type, it’s extension can be jpeg,png,jpg,gif,svg and the image can have a max of 2MB in size.
Perfect, then while uploading image, we are doing it in 2 step. Firstly, we are creating a new unique file name with the time() function in $imageName.
Then with $image->move(...), we are moving the uploaded image in our application with renamed as new name. This directory will be under public/images generally.
After that, with Image::create(), we are saving the image name to our database.
deleteImage: with the deleteImage method, we undoing the same thing we did while storing the image. First we are checking if our server holds the image in the images directory with the saved name, if found it is deleting the file from the directory.
And then we are deleting record from database.
Now lets add the view
Now the hard part is completed. In the view there will also be two parts. One is a form to upload image and another is to show the uploaded image with a delete button.
Lets make a view file under resources/views/upload.blade.php like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
</head>
<body>
@if (session('success'))
<div>{{ session('success') }}</div>
@endif
@if (session('error'))
<div>{{ session('error') }}</div>
@endif
<form action="{{ url('/upload') }}" method="post" enctype="multipart/form-data">
@csrf
<div>
<label for="image">Choose an image:</label>
<input type="file" name="image" id="image" required>
</div>
<button type="submit">Upload</button>
</form>
<h2>Uploaded Images</h2>
@foreach($images as $image)
<div>
<img src="{{ url('images/' . $image->name) }}" alt="Uploaded Image" style="width: 100px;">
<form action="{{ url('/upload/' . $image->id) }}" method="post" style="display: inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</div>
@endforeach
</body>
</html>
Now run the code
Done, you can now run the code and test image upload with ‘/upload’ route:
Php artisan serve
Summary
So thats a basic way how we can upload images in laravel. We used basic php functions instead of using any laravel packages. I have shown for images, but you can use this way for uploading other kind of assets like document, pdf, video etc too.
Thank you for reading this post. Hope you have found this useful. Let me know your thoughts in the comments and please give a love to this article.
Wish you a happy day.
Comments