I am trying to upload a photo and store it in a specific path. When in the controller function it is going to validate if in a hasFile type field it does if ($request->hasFile($request->input('avatar')))
not take the field as a file type and it does not save the uploaded photo in the specified path
This is the code I have implemented:
In blades:
<form id="example-form" method="post" enctype="multipart/form-data">
<span class="profile-picture">
<input type="file" id="pic" name="avatar"/>
</span>
<div class="space-4"></div>
<a onclick="change_imagen_avatar(12)" class="btn btn-sm btn-block btn-info">
<span class="bigger-110">Aceptar</span>
</a>
<div class="space-4"></div>
<a id="cancelar_foto" class="btn btn-sm btn-block btn-grey">
<span class="bigger-110">Cancelar</span>
</a>
</form>
JavaScript:
function change_imagen_avatar(id){
$.ajax({
type: 'POST',
url: '{{ route('regMiembros.change_imagen_avatar') }}',
data: {
avatar: $('#id-input-file-3').val(),
miembro: id,
},
success: function (data) {
alert('Hola');
//$(location).attr('href', "{{ route('regMiembros.show', [$regMiembro->id]) }}");
},
error: function (jqXHR, textStatus, errorThrown) {
$.smkAlert({
text: jqXHR.responseText,
type: 'danger'
});
}
});
}
In Controller:
public function change_imagen_avatar(Request $request){
$input = $request->all();
$personas = Personas::find($input['miembro']);
if ($request->hasFile($request->input('avatar'))) {
$avatar = $request->file('avatar');
$filename = $personas->nom_apellido . '.png';
Image::make($avatar)->save(public_path('/uploads/hermanos/' . $filename));
$input['avatar'] = $filename;
}
$personas->avatar = $input['avatar'];
$personas->save();
}
your error is how you send the image to the server, it must be through formData .
you must also add the csrf_token either in your form or in your meta in this example we will use the meta added in the head of the document! in case your js is external:
or add it to the ajax request as a header:
HTML code
There are several things to improve: In order
controller
to verify if the file is present, you have to do it as follows:In the
Client
: