I'm trying to modify a record. This record contains an image and can also be modified. I don't know how to modify the image that is saved in a public directory in the project.
This is my code for uploading images(it takes place inside my bootstrap model).When I upload the image,and click on the submit button,the image should inserted into db and the same should be retrieved and displayed on the view page.
How to add FormData in ajax?
Blade
<div class="modal fade" id="sacrificeModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="sacrificeModal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="sacrificeModal">ویرایش عنوان افتخار</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="post" id="sacrificeFormUpdate">
@csrf
@method('PUT')
<input type="hidden" id="id">
<div class="row">
<div class="col-md-6 mb-3">
<label for="edit_sacrifice">Sacrifice</label>
<input type="text" class="form-control" id="edit_sacrifice" name="sacrifice">
</div>
<div class="col-md-6 mb-3">
<label for="edit_file">آFile</label>
<input type="file" class="form-control" id="edit_file" name="file">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="sacrificeUpdate">Save</button>
</div>
</div>
</div>
</div>
script
$(document).on('click', '#sacrificeEdit', function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type:'get',
url:'/sacrifice/'+id+'/edit',
success:function (data) {
console.log(data);
$('#id').val(data.sacrifice.id);
$('#edit_sacrifice').val(data.sacrifice.sacrifice);
$('#edit_file').val(data.sacrifice.file);
},
})
});
$(document).on('click', '#sacrificeUpdate', function(event) {
event.preventDefault();
var id = $('#id').val();
var data = {
'sacrifice' : $('#edit_sacrifice').val(),
'file' : $('#edit_file').val(),
}
var formData = new FormData($('#sacrificeFormUpdate')[0]);
$.ajax({
type: 'PUT',
url: '/sacrifice/'+id,
data: [data, formData],
success: function (response) {
console.log(response);
$('#sacrificeModal').modal('hide');
showSacrifice();
},
});
});
Controller
public function update(Request $request, Sacrifice $sacrifice)
{
$fileName = $request->fileSacrifice == $request->fileSacrifice ? $request->fileSacrifice : null;
if ($request->hasFile('fileSacrifice'))
{
$file = $request->file('fileSacrifice');
$nane = time();
$extension = $file->getClientOriginalExtension();
$fileName = $nane . '.' . $extension;
$file->move(public_path('files/sacrifices'), $fileName);
}
$data = [
'sacrifice' => $request->sacrifice,
'fileSacrifice' => $fileName,
];
$sacrifice->update($data);
return response()->json($sacrifice);
}