Don't tag people for their input as this puts off all the other great helpers on this site.
Where does that message come from and where do you see it?
I am building an image preview with session, the issue I am facing is that I am getting an error below image field "Image failed to upload"
My goal is to attain:
What needs to happen:
This is my logic in controller
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'bird_name' => 'required|string|unique:birds,bird_name',
'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
'image_alt_tag' => 'required|string|unique:birds,bird_alt_tag',
'status' => 'required|in:1,2'
]);
if ($request->hasFile('image')) {
$file = $request->file('image');
// Validate image separately for size and type
$imageValidator = Validator::make(['image' => $file], [
'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
]);
// Step 3: If the image is valid, upload it to a temporary location for preview
if (!$imageValidator->fails()) {
$filename = 'temp_' . bin2hex(random_bytes(10)) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('uploads/temp'), $filename);
// Store the filename in the session for preview
$fileHash = md5($filename);
$request->session()->put('pending_upload_' . $fileHash, $filename);
$request->session()->put('pending_upload_hash', $fileHash);
} else {
// If the image is invalid, clear any pending image preview
$request->session()->put('pending_upload_hash', null);
}
}
// Stop if validation fails
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
try {
$fileHash = $request->session()->get('pending_upload_hash');
$fileName = $request->session()->get('pending_upload_' . $fileHash);
DB::beginTransaction();
$bird = new Bird();
$bird->bird_name = $request->bird_name;
$bird->bird_img = $fileName;
$bird->bird_alt_tag = $request->image_alt_tag;
$bird->status = $request->status;
$bird->created_by = Auth::user()->id;
$bird->created_at = now();
$bird->save();
if ($fileName && File::exists(public_path('uploads/temp/' . $fileName))) {
$finalPath = public_path('website/bird/' . $fileName);
if (!File::exists(public_path('website/bird'))) {
File::makeDirectory(public_path('website/bird'), 0755, true);
}
File::move(public_path('uploads/temp/' . $fileName), $finalPath);
$request->session()->forget('pending_upload_' . $fileHash);
$request->session()->forget('pending_upload_hash');
}
DB::commit();
return redirect()->route('staffAdmin.listBird')->with('success', 'Bird Added Successfully.');
} catch (\Exception $exp) {
DB::rollBack();
return redirect()->back()->withInput()->with('error', $exp->getMessage());
}
}
This code is working, preview is also working , image getting uploaded to temp folder as well, but error below image field "Image failed to upload" comes up.
What do I observed, if I removed this part, this error gets omitted "Image failed to upload
if ($request->hasFile('image')) {
$file = $request->file('image');
// Validate image separately for size and type
$imageValidator = Validator::make(['image' => $file], [
'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:500',
]);
// Step 3: If the image is valid, upload it to a temporary location for preview
if (!$imageValidator->fails()) {
$filename = 'temp_' . bin2hex(random_bytes(10)) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('uploads/temp'), $filename);
// Store the filename in the session for preview
$fileHash = md5($filename);
$request->session()->put('pending_upload_' . $fileHash, $filename);
$request->session()->put('pending_upload_hash', $fileHash);
} else {
// If the image is invalid, clear any pending image preview
$request->session()->put('pending_upload_hash', null);
}
}
How to fix this?
I can't use ajax, as requirement is strictly avoid ajax to me. @Snapey @tykus @Sinnbeck please
This is the logics from controller
public function create(Request $request)
{
// $fileHash = $request->session()->get('pending_upload_hash');
// $filePath = $fileHash ? $request->session()->get('pending_upload_' . $fileHash) : null;
if (!$request->old()) {
$fileHash = $request->session()->get('pending_upload_hash');
if ($fileHash) {
$request->session()->forget('pending_upload_hash');
$request->session()->forget('pending_upload_' . $fileHash);
}
}
$fileHash = $request->session()->get('pending_upload_hash');
$filePath = $fileHash ? $request->session()->get('pending_upload_' . $fileHash) : null;
return view('staffAdmin.bird_add', compact('fileHash', 'filePath'));
}
public function store(Request $request)
{
// $request->session()->forget('pending_upload_hash');
// $request->session()->forget('pending_upload_' . $request->session()->get('pending_upload_hash'));
$imageValidationRule = $request->session()->has('pending_upload_hash') ? 'nullable|image|mimes:jpg,jpeg,png,webp|max:500' : 'required|image|mimes:jpg,jpeg,png,webp|max:500';
$validator = Validator::make($request->all(), [
'bird_name' => 'required|string|unique:birds,bird_name',
'image' => $imageValidationRule,
'image_alt_tag' => 'required|string|unique:birds,bird_alt_tag',
'status' => 'required|in:1,2'
]);
// If validation fails, handle the image preview
if ($validator->fails()) {
// If there are image validation errors, don't store the preview
// if ($validator->errors()->has('image')) {
// $request->session()->forget('pending_upload_hash');
// $request->session()->forget('pending_upload_' . $request->session()->get('pending_upload_hash'));
// }
// Handle image only if it's present and passes image validation
if ($request->hasFile('image') && !$validator->errors()->has('image')) {
$file = $request->file('image');
$filename = 'temp_' . bin2hex(random_bytes(10)) . '.' . $file->getClientOriginalExtension();
// Remove old temp file if exists
$oldHash = $request->session()->get('pending_upload_hash');
if ($oldHash) {
$oldPath = $request->session()->get('pending_upload_' . $oldHash);
if ($oldPath && File::exists(public_path('uploads/temp/' . $oldPath))) {
File::delete(public_path('uploads/temp/' . $oldPath));
}
}
// Move new image to temp folder
$file->move(public_path('uploads/temp'), $filename);
$fileHash = md5($filename);
$request->session()->put('pending_upload_' . $fileHash, $filename);
$request->session()->put('pending_upload_hash', $fileHash);
}
// Return with validation errors and old input
return redirect()->back()->withErrors($validator)->withInput();
}
try {
$fileHash = $request->session()->get('pending_upload_hash');
$fileName = $request->session()->get('pending_upload_' . $fileHash);
DB::beginTransaction();
// Create the bird record
$bird = new Bird();
$bird->bird_name = $request->bird_name;
$bird->bird_img = $fileName;
$bird->bird_alt_tag = $request->image_alt_tag;
$bird->status = $request->status;
$bird->created_by = Auth::user()->id;
$bird->created_at = now();
$bird->save();
// If file exists, move it to the final directory
if ($fileName && File::exists(public_path('uploads/temp/' . $fileName))) {
$finalPath = public_path('website/bird/' . $fileName);
File::move(public_path('uploads/temp/' . $fileName), $finalPath);
// Forget the session data for the pending upload
$request->session()->forget('pending_upload_' . $fileHash);
$request->session()->forget('pending_upload_hash');
}
DB::commit();
return redirect()->route('staffAdmin.listBird')->with('success', 'Bird Added Successfully.');
} catch (\Exception $exp) {
DB::rollBack();
return redirect()->back()->withInput()->with('error', $exp->getMessage());
}
}
This is from my blade
<div class="col-md-8 offset-md-2 mb-3 form-group">
<div class="bg-light text-center rounded p-5 mt-2 mb-4">
<div class="div-preview-img">
@if($errors->any() && !$errors->has('image'))
@if($fileHash && $filePath && file_exists(public_path('uploads/temp/' . $filePath)))
<img src="{{ asset('uploads/temp/' . $filePath) }}" id="imgPreview" class="preview-img" alt="Preview Image">
@else
<img src="{{ asset('website/assets/img/demo/default-logo.png') }}" id="imgPreview" class="preview-img" alt="Preview Image">
@endif
@else
<img src="{{ asset('website/assets/img/demo/default-logo.png') }}" id="imgPreview" class="preview-img" alt="Preview Image">
@endif
</div>
</div>
<div class="row">
<div class="col-12 mb-3">
<label class="form-label">Image
@if($errors->any() && !$errors->has('image'))
@if($fileHash && $filePath && file_exists(public_path('uploads/temp/' . $filePath)))
@else
<span class="text-danger">*</span>
@endif
@else
<span class="text-danger">*</span>
@endif
</label>
<div class="controls">
<input class="form-control file-input" name="image" id="image" type="file" accept="image/jpeg,image/png,image/webp" data-preview-id="imgPreview">
<small>Best size to upload is 300 x 80 (px). Only JPEG, JPG, PNG, and WEBP supported. Maximum size allowed 500KB.</small>
@error('image')
<div class="error text-danger fs-2">{{ $message }}</div>
@enderror
</div>
</div>
</div>
</div>
Please or to participate in this conversation.