I’m Using Laravel 5.8, I’m trying to make update data in laravel, the data is contained images, when the form update did not get a new image, laravel displays an error, that the image is null, can I make the old image as the default value for the file input?
this is my controller
public function UploadEdit(Request $request, Books $book,$id_book){ $book = Books::find($id_book); global $old_image; $old_image = public_path("img/books/". $book->image); if($request->hasFile('image')){ if (File::exists($old_image)) { unlink($old image); } $image = $request->file('image'); $image_name = time()."_".$image->getClientOriginalName(); $image->move('img/books',$image_name); $book->image=$image_name; }else{ $book->image = $old_image; } DB::table('books')->where('id_book',$request->id_book,$image_name)->update([ 'title' => $request->title, 'image' => $request->image = $image_name, 'category' => $request->category, 'description' => $request->description ]); return redirect('/books'); }
this is input file from my form :
<div class="form-group"> <label for="image">Image</label> <input type="file" class="form-control-file" id="image" name="image" id="image" enctype="multipart/form-data" value="{{ asset("img/books/$book->image") }}"> <img src="{{ asset("img/books/$book->image") }}" width="150"> </div>
I’m trying to make the default value for file form, but still doesn’t work
Advertisement
Answer
You can’t set default value for <input type="file"/>
the best thing you can do is when you’re updating books table check if request has image if it doesn’t then you can skip updating image or reassign previous one
here is what it looks like
DB::table('books')->where('id_book',$request->id_book,$image_name)->update([ 'title' => $request->title, 'image' => $request->hasFile('image') ? $image_name : $book->image, 'category' => $request->category, 'description' => $request->description ]);