<h3>Step 1: Create a Form for Image Upload</h3>
<p>Create a Blade view for the image upload form.</p>
<div class=”dark bg-gray-950 rounded-md border-[0.5px] border-token-border-medium”>
<div class=”flex items-center relative text-token-text-secondary bg-token-main-surface-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md”>blade
<div class=”flex items-center”> </div>
</div>
</div>
Table of Contents
Toggleuse App\Http\Controllers\ImageUploadController;
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.
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’, ], ],
In the ImageUploadController
, add the following methods:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
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.
<!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 class=”container mt-5″>
<h2>Upload Image</h2>
@if (session(‘success’))
<div class=”alert alert-success”>
{{ session(‘success’) }}
</div>
<div>
<img src=”{{ Storage::url(session(‘image’)) }}” class=”img-fluid” />
</div>
@endif
<form action=”{{ route(‘upload.image’) }}” method=”POST” enctype=”multipart/form-data”>
@csrf
<div class=”form-group”>
<label for=”image”>Choose Image</label>
<input type=”file” class=”form-control” name=”image” id=”image” required>
</div>
<button type=”submit” class=”btn btn-primary”>Upload</button>
</form>
</div>
</body>
</html>