Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <template>
- <div class="tab-pane" id="settings">
- <form @submit.prevent="updateReg()" class="form-horizontal" novalidate>
- <!-- ... -->
- <div class="form-row">
- <div class="col-md-4 mb-1">
- <div class="form-group mb-0">
- <div class="row">
- <div class="col-8 mx-auto text-center">
- <img class="input-img-avatar" :src="avatar" alt="Imagen de usuario seleccionada">
- </div>
- </div>
- <div class="row mt-0">
- <div class="col-8 mx-auto text-center">
- <label class="btn-bs-file btn btn-primary">
- Cargar nuevo avatar
- <input type="file" name="avatar" @change="getNewAvatar" accept="image/*" ref="inputFileAvatar" />
- </label>
- <span v-if="errors.has('avatar')" class="block text-sm text-danger mt-2">{{ errors.get('avatar') }}</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="form-row">
- <div class="col-md-12 col-sm-offset-2 col-sm-10 text-right">
- <button type="submit" class="btn btn-success" title="Actualizar registro">Actualizar</button>
- </div>
- </div>
- </form>
- .btn-bs-file{
- position:relative;
- font-weight: normal !important;
- }
- .btn-bs-file input[type="file"]{
- position: absolute;
- top: -9999999;
- filter: alpha(opacity=0);
- opacity: 0;
- width:0;
- height:0;
- outline: none;
- cursor: inherit;
- }
- <script>
- //librería para tratar los errores capturados en el servidor
- import { Errors } from '../../libs/errors';
- export default {
- mounted() {
- console.log('Component mounted.');
- //Recibiendo evento(s) si emitido(s) (en este caso, desde su componente Padre)
- BusEvent.$on('fillProfEditFormEvent', (regID) => {
- this.fillEditFormReg(regID);
- });
- },
- //datos devueltos por el componente:
- data() {
- return {
- urlBase: '/api/admin/users',
- //variable que guarda el archivo seleccionado
- //indicando nombre del archivo precedido de la ruta completa
- //hacia el archivo guardado en el servidor
- avatar: null,
- avatar_max_size: null,
- //variable para almacenar los datos del registro a almacenar
- //objReg: {},
- objReg: {
- 'name': '',
- 'lastname': '',
- 'phone_int': '',
- //y más datos que no pongo para que no sea más largo
- 'avatar': '',
- //para la edición
- 'id': '',
- },
- //posibles errores
- errors: new Errors(),
- }
- },
- methods: {
- /**
- * Mostrando datos cargados del registro para editar
- */
- fillEditFormReg(regID) {
- console.log('Cargando datos del registro correspondiente [' + regID + ']');
- let url = this.urlBase + '/' + regID;
- axios.get(url)
- .then(response => { //SI TODO OK
- console.log(response.data)
- //this.objReg = response.data
- //this.objReg = response.data.user
- this.objModelDependenciesLists = response.data.dependenciesLists
- this.objReg = {
- 'name': response.data.user.name,
- 'lastname': response.data.user.lastname,
- 'phone_int': response.data.user.phone_int,
- //...
- 'avatar': response.data.user.avatar,
- //...
- //para la edición
- 'id': response.data.user.id,
- };
- this.avatar_max_size = response.data.user_icon_max_size
- this.avatar = `/storage/images/profile/${this.objReg.avatar}`
- //carga inicial de la imagen precedida de su ruta
- })
- .catch(error => { //SI HAY ALGÚN ERROR
- console.log(error.response.data.errors);
- });
- },
- /**
- * Lanzado al cambiar el valor del input de archivo del formulario
- */
- getNewAvatar(e) {
- let file = e.target.files[0];
- //Sacando características referidas al archivo cargado
- //en el input de archivo dentro de un array JSON
- console.log(file);
- if(file['size'] <= this.avatar_max_size) {
- //Leyendo el archivo cargado
- this.readFile(file);
- } else {
- //Reseteando valor...
- this.cancelFileAction();
- alert('El archivo cargado tiene un tamaño en disco más grande de lo permitido.');
- }
- },
- readFile(file) {
- let reader = new FileReader();
- reader.readAsDataURL(file);
- reader.onload = e => {
- //Pasando la imagen seleccionada en Base64 a la variable
- //que se caraga en la etiqueta IMG
- this.avatar = e.target.result;
- console.log('Esto es ahora AVATAR: ' + this.avatar)
- //Asignando la imagen seleccionada en Base64 a
- //la propiedad 'avatar' del objeto objReg
- this.$set(this.objReg, 'avatar', e.target.result)
- }
- },
- cancelFileAction() {
- //Reseteando imagen y volviendo a valor anterior...
- this.avatar = `/storage/images/profile/${this.objReg.avatar}`;
- //Limpiando elementos...
- this.clearFileAction();
- },
- clearFileAction() {
- //Reseteando imagen y volviendo a valor anterior...
- //Reseteando contenido del INPUT File
- const input = this.$refs.inputFileAvatar;
- input.type = 'text';
- input.type = 'file';
- },
- /**
- * Actualizando registro
- */
- updateReg() {
- console.log('Actualizando registro... [' + this.objReg.id + ']');
- let url = this.urlBase + '/' + this.objReg.id;
- axios.put(url, this.objReg)
- .then((response) => { //SI TODO OK
- //vaciando los posibles errores que se produjeron
- this.errors.clear();
- //Emitiendo evento global para recargar
- //en el panel izquierdo de datos resumen
- // >> con el ID pasado
- BusEvent.$emit('fillProfDataResumEvent', this.objReg.id);
- //Lanzando notificación satisfactoria
- toast({
- type: 'success',
- title: 'Registro actualizado'
- });
- })
- .catch(error => { //SI HAY ALGÚN ERROR
- //registrando los errores recibidos
- this.errors.record(error.response.data.errors);
- });/**/
- },
- },
- }
- </script>
- public function update(UserUpdateRequest $request, $id)
- {
- $user = User::withTrashed()->findOrFail($id);
- $user->name = $request->name;
- $user->lastname = $request->lastname;
- //...
- //USERNAME
- $user->username = Str::slug($request->name . ' ' . $request->lastname);
- //AVATAR
- //Si existe un valor para este INPUT...
- $hay_foto = '';
- $name_file = '';
- $user_username = '';
- //return $request->all();
- if($request->has('avatar')) {
- //if($request->hasFile('avatar')) {
- //if($request->avatar) {
- $hay_foto = 'SI hay';
- $user_username = $user->username;
- $extension_file = explode(';', explode('/', $request->avatar)[1] )[0];
- $name_file = $user->username . '.' . $extension_file;
- //Guardando archivo en STORAGE
- $request->avatar->storeAs('public' . '/images/profile', $name_file);
- //$request->file('avatar')->storeAs('public' . '/images/profile', $name_file);
- $user->avatar = $name_file;
- } else {
- $hay_foto = 'NO hay';
- }
- //Si no es NULO
- if( !is_null($request->password) ) {
- $user->password = Hash::make($request->password);
- }
- $user->profile_id = $request->profile_id;
- $user->save();
- return [
- 'message' => 'Actualizando el registro con ID => [' . $id . ']',
- 'avatar' => $request->avatar,
- 'name_file' => $name_file,
- 'user_username' => $user_username,
- 'hay_foto' => $hay_foto,
- ];
- }
- $request->avatar->storeAs('public' . '/images/profile', $name_file);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement