Image upload feature in Laravel, where the images are stored in monthly-based folders
<h3>Step 1: Create a Form for Image Upload</h3>
<p>Create a Blade view for the image upload form.</p>
<div>
<div>blade
<div> </div>
</div>
</div>
use AppHttpControllersImageUploadController;
Route::get(‘upload’, [ImageUploadController::class, ‘showUploadForm’]);
Route::post(‘upload’, [ImageUploadController::class, ‘uploadImage’])->name(‘upload.image’);
Step 3: Create a Controller
Generate a controller to handle the image upload logic.
php artisan make:controller ImageUploadController
Step 4: Configure Filesystem
Ensure your config/filesystems.php
is configured to use the public
disk.
‘disks’ => [ ‘public’ => [ ‘driver’ => ‘local’, ‘root’ => storage_path(‘app/public’), ‘url’ => env(‘APP_URL’).’/storage’, ‘visibility’ => ‘public’, ], ],
php
In the ImageUploadController
, add the following methods:
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesStorage;
use IlluminateSupportStr;
class ImageUploadController extends Controller
{
public function showUploadForm()
{
return view(‘upload’);
}
public function uploadImage(Request $request)
{
$request->validate([
‘image’ => ‘required|image|mimes:jpeg,png,jpg,gif|max:2048’,
]);
$image = $request->file(‘image’);
// Create a monthly based folder
$monthYear = now()->format(‘Y-m’);
$folder = ‘uploads/images/’ . $monthYear;
$filename = Str::random(20) . ‘.’ . $image->getClientOriginalExtension();
// Store the image
$path = $image->storeAs($folder, $filename, ‘public’);
return back()
->with(‘success’, ‘Image uploaded successfully.’)
->with(‘image’, $path);
}
}
Step 5: Link Storage
Run the following command to create a symbolic link from public/storage
to storage/app/public
.
php artisan storage:link
Step 6: Handle the Uploaded Image
Update the upload.blade.php
view to show the uploaded image.
<!– resources/views/upload.blade.php –>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”>
</head>
<body>
<div>
<h2>Upload Image</h2>
@if (session(‘success’))
<div>
{{ session(‘success’) }}
</div>
<div>
<img src=”{{ Storage::url(session(‘image’)) }}” />
</div>
@endif
<form action=”{{ route(‘upload.image’) }}” method=”POST” enctype=”multipart/form-data”>
@csrf
<div>
<label for=”image”>Choose Image</label>
<input type=”file” name=”image” id=”image” required>
</div>
<button type=”submit”>Upload</button>
</form>
</div>
</body>
</html>