@domenico
In Laravel, you can use the built-in validation feature to validate an uploaded image. Here is a step-by-step guide on how to validate an image in Laravel:
1 2 3 |
$validatedData = $request->validate([ 'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048' // max size in kilobytes ]); |
In this example, the image field is required, must be an image file, and must have an allowed mime type (jpeg, png, jpg, gif). The maximum file size is also specified (2MB in this case).
1 2 3 4 5 |
<form method="POST" action="/upload" enctype="multipart/form-data"> @csrf <input type="file" name="image"> <button type="submit">Upload Image</button> </form> |
1 2 3 4 5 6 7 |
$image = $request->file('image'); $fileName = time() . '.' . $image->getClientOriginalExtension(); $filePath = 'images/' . $fileName; Storage::disk('public')->put($filePath, file_get_contents($image)); // Save file path to database or perform other operations |
1 2 3 4 5 |
@if ($errors->has('image')) <div class="alert alert-danger"> {{ $errors->first('image') }} </div> @endif |
By following these steps, you can successfully validate an image upload in a Laravel application.