I'm new to coding and I want to upload a product image upon completing of the new product form in a modal tag in my blade.php.
However, my data are unable to be posted into the database and the file is also not uploading to the server. Please kindly advise on what I should do to solve this issue. Thanks in advance!
This is my View:
<form action="{{route('merchant.product.new')}}" id="form" method="POST" enctype="multipart/form-data">
@csrf
<div class="modal-body">
<div class="form-group">
<label for="prodName"> Product Name:</label> <small style="color: red">*</small>
<input type="text" id="prodName" class="form-control" name="prodName" value="" maxlength="55" placeholder="Product Name" required>
</div>
<div class="form-group">
<label for="prodCode"> Product Code:</label> <small style="color: red">*</small>
<input type="text" id="prodCode" class="form-control" name="prodCode" value="" maxlength="55" placeholder="Product Code" required>
</div>
<div class="form-group">
<label for="prodDesc"> Description:</label> <small style="color: red">*</small>
<textarea id="prodDesc" name="prodDesc" rows="5" maxlength="255" placeholder="Product Description" class="form-control" required></textarea>
</div>
<div class="form-group">
<label for="age">Price:</label> <small style="color: red">*</small>
<input type="text" id="price" class="form-control" name="price" placeholder="Product Price" required>
</div>
<div class="form-group">
<label for="age">Quantity:</label>
<input type="number" id="quantity" class="form-control" name="Quantity" min="0" value="0">
</div>
<div class="form-group">
<label for="text">Feature Product</label>
<div class="switch">
<input type="checkbox" name="featured" id="featured" class="switch-input" value="1"/>
<div class="circle"></div>
</div>
</div>
<div class="form-group">
<label for="image">Choose Main Image</label>
<input type="file" name="image" id="image">
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="new_productsave_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Save</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</form>
Below is my script:
$(document).ready(function(e) {
var selectedProductId = null;
var selectedProductCode = null;
var pageAction = null;
//javascript to filter table
var productsTable = $('#products_table').DataTable({
stateSave: true,
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
},{
"searchable": true,
"orderable": true,
"targets": 1
},{
"searchable": true,
"orderable": true,
"targets": 2
},{
"searchable": false,
"orderable": false,
"targets": 3
},{
"searchable": true,
"orderable": true,
"targets": 4
},{
"searchable": true,
"orderable": true,
"targets": 5
},{
"searchable": true,
"orderable": true,
"targets": 6
},{
"searchable": false,
"orderable": false,
"targets": 7
}],
order: [[ 1, 'asc' ]]
});
productsTable.on( 'order.dt search.dt', function () {
productsTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
});
}).draw();
$('#addproduct_btn').click(function() {
//pageAction = "add";
$('#myModalNewProduct').modal({backdrop: 'static', keyboard: false});
$('#myModalNewProduct .modal-title').html('New Product');
});
$('#new_productsave_btn').click(function() {
let prodName = $('#prodName').val();
let prodCode = $('#prodCode').val();
let prodDesc = $('#prodDesc').val();
let price = parseFloat($('#price').val().replace(/[^\d.]/g, ''));
let quantity = $('#quantity').val();
var featured = [];
$('#featured').each(function(){
if ($(this).is(":checked")) {
featured.push($(this).val());
}
});
featured = featured.toString();
if (prodCode == "") {
alert("Product Code can't be empty.");
return;
}
if (prodDesc == "") {
alert("description can't be empty.");
return;
}
if (price == "") {
alert("price can't be empty.");
return;
}
if (Number.isNaN(price)) {
alert("price must be numeric.");
}
//let url = pageAction == "add" ? @json($domain)+"/products/new" : @json($domain)+"/products/update";
let data = {prodID: selectedProductId, prodName: prodName, prodCode: prodCode, prodDesc: prodDesc, quantity: quantity, price: price,
featured: featured,
};
$(this).data('original-text', $(this).html()).html($(this).data('loading-text')).prop('disabled', true);
$.ajax({
type: "POST",
url: "{{ route('merchant.product.new') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "text",
success: function(data) {
if (data == 0) {
$('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
showNotify("Product Code already exist", "error");
return;
} else if (data < 0) {
$('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
showNotify("Something went wrong", "error");
return;
}
showNotify("New product has been added successfully", "success");
location.reload();
},
error: function(data) {
$('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
console.log(data);
showNotify("Something went wrong", "error");
}
});
});
});
Below is my dd($request->all())
array:7 [▼
"_token" => "pfPg4Grw7MXzDQwBeDAcBN83sZm06LK89GzlNdbY"
"prodName" => "123213"
"prodCode" => "123123"
"prodDesc" => "123213"
"price" => "123123"
"Quantity" => "123"
"image" => Illuminate\Http\UploadedFile {#359 ▼
-test: false
-originalName: "roasted-chicken.png"
-mimeType: "image/png"
-error: 0
#hashName: null
path: "C:\xampp\tmp"
filename: "php6D72.tmp"
basename: "php6D72.tmp"
pathname: "C:\xampp\tmp\php6D72.tmp"
extension: "tmp"
realPath: "C:\xampp\tmp\php6D72.tmp"
aTime: 2021-01-13 10:25:05
mTime: 2021-01-13 10:25:05
cTime: 2021-01-13 10:25:05
inode: 5066549581112407
size: 699931
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\xampp\tmp\php6D72.tmp"
}
]
This is my controller method:
public function new (Request $request) {
if ($this->isCodeExist($request->{'prodCode'})) {
return 0;
}
else {
$product = Product::create($request->all());
if($request->hasFile('image')) {
// Upload path
$destinationPath = 'img/products/';
// Get File
$image = $request->file('image');
// Get File Name
$imageName = time().'_'.$image->getClientOriginalName();
// Uploading File to given path
$image->move($destinationPath,$imageName);
// $fileModel->name = time().'_'.$req->file->getClientOriginalName();
// $fileModel->file_path = '/storage/' . $filePath;
// $fileModel->save();
try {
//$db = new Product();
$product->prodName = $request->{'prodName'};
$product->prodCode = $request->{'prodCode'};
$product->prodImage = $imageName;
$product->prodDesc = $request->{'prodDesc'};
$product->price = $request->{'price'};
$product->quantity = $request->{'quantity'};
$product->featured = $request->input('featured') ? 1 : 0;
$dproductb->save();
return 1;
} catch (\Illuminate\Database\QueryException $ex) {
Log::channel('merchant_error')->error($ex);
return -1;
}
}
}
}