Can't get file name and extension in the variable "$fileNameToStore" but it is able to save default image name {'noimage.jpg'} in database. i want to know what is the cause for that.
public function store(Request $request)
{
$this->validate($request, [
'img' => 'nullable|max:1999'
// 'phone' => 'required'
]);
//handle file
$fileNameToStore = 'noimage.jpg';
if($request->hasFile('img')){
//get file name and extension
$filenameWithExt = $request->file('img')->getClientOriginalName();
//get just file name
$filename = $request->file('img')->getClientOriginalName();
//get just extension
$extension = $request->file('img')->getClientOriginalExtension();
//file name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//upload the image
$path = $request->file('img')->storeAs('public/product_images', $fileNameToStore);
}
//create product
$product = new Product;
$product->type = $request->input('type');
$product->img = $fileNameToStore;
$product->details = $request->input('details');
$product->save();
$notification = array(
'message' => 'Ürün kaydedildi !',
'alert-type' => 'success'
);
return redirect('/urungir')->with($notification);
}
The cause of this issue is that, in the form that submits to the controller, there is a mistake as shown below, The enctype="multipart/data"
is wrong and in order to fix the problem, it should change to: enctype="multipart/form-data"
// Wrong :
<form class="form-horizontal" action="/products" method="post" enctype="multipart/data" id="urungirform">
{{ csrf_field() }}
<input type="file" name="img">
</form>
// Correct :
<form class="form-horizontal" action="/products" method="post" enctype="multipart/form-data" id="urungirform">
{{ csrf_field() }}
<input type="file" name="img">
</form>