laravel vue getting info by hidden field

China☆狼群 提交于 2021-01-29 12:47:58

问题


I need to pass logged user id to back-end and I have vuex store so I can get my user info like {{currentUser.id}} the problem is i cannot pass it to back-end it gives me validation error that user_id is required while i have this hidden input in my form

<input type="hidden" name="user_id" :value="currentUser.id">

for normal inputs i have v-model like v-model="project.title" which is not possible to use on hidden fields.

The question here is how can I pass my user_id to back-end?

Code

<script>
import validate from 'validate.js';

    export default {
        data: function () {
            return {
                project: {
                    title: '',
                    body: '',
                    attachment: '',
                    projectclass: '',
                    deadline: '',
                    user_id: '',
                    csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                },
                errors: null
            }
        },
        computed: {
            currentUser() {
                return this.$store.getters.currentUser;
            }
        },
        methods: {
            add() {
                this.errors = null;
                const errors = validate(this.$data.project);
                if(errors) {
                    this.errors = errors;
                    return;
                }
                axios.post('/api/projects/new', this.$data.project)
                .then((response) => {
                    this.$router.push('/projects');
                });
            }
        }
    }
</script>

回答1:


This happens because user_id in this.$data.project dosn't get updated.

Instead of having hidden input you can just do

add() {
   this.errors = null;
   const errors = validate(Object.assign(this.$data.project, {user_id: this.currentUser.id}));
   if(errors) {
      this.errors = errors;
      return;
   }
   axios.post('/api/projects/new', Object.assign(this.$data.project, {user_id: this.currentUser.id}))
     .then((response) => {
         this.$router.push('/projects');
      });
}


来源:https://stackoverflow.com/questions/51788294/laravel-vue-getting-info-by-hidden-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!