Skip to content
Advertisement

How to assign value in VueJS with Laravel?

How do you assign laravel value like this {{ auth->()->user()->first_name }}

on this vuejs textfield

 <input v-model="user.first_name" type="text"
 class="form-control form-control-lg rounded-0" :value="{{ auth()->user()->first_name }}">

Here’s the original html show.blade.php

<form class="my-3 font-sans-serif">
                            <div class="form-group">
                                <label for="" class="font-weight-semibold text-uppercase">First Name*</label>
                                <input v-model="user.first_name" type="text"
                                       class="form-control form-control-lg rounded-0">
                                <span class="text-danger text-xs">@{{ errors.first_name }}</span>
                            </div>
                            <div class="form-group">
                                <label for="" class="font-weight-semibold text-uppercase">Last Name</label>
                                <input v-model="user.last_name" type="text"
                                       class="form-control form-control-lg rounded-0">
                                <span class="text-danger text-xs">@{{ errors.last_name }}</span>
                            </div>
                            <div class="form-group">
                                <label for="" class="font-weight-semibold text-uppercase">Email*</label>
                                <input v-model="user.email" type="email"
                                       class="form-control form-control-lg rounded-0">
                                <span class="text-danger text-xs">@{{ errors.email }}</span>
                            </div>
                            <div class="form-group">
                                <label for="" class="font-weight-semibold text-uppercase">Phone</label>
                                <input v-model="user.phone" type="text"
                                       class="form-control form-control-lg rounded-0">
                                <span class="text-danger text-xs">@{{ errors.phone }}</span>
                            </div>
                            <button @click.prevent="submit" class="btn btn-primary w-100 text-white mt-4 mb-3">
                                Submit
                            </button>
                        </form>

I’m a beginner in vuejs.

Note: This laravel code {{ auth->()->user()->first_name }} has a valid value since the user used is logged in.

I need to study the vuejs I only knew the basics.

Here’s the code showvue.js

const app = new Vue({
el: '#property-booking',
data: {
    units: units,
    guest: 2,
    dates: [],
    selectedDates: [],
    rates: [],
    user: {
        first_name: '',
        last_name: '',
        email: '',
        phone: ''
    },
    errors: {
        first_name: '',
        last_name: '',
        email: '',
        phone: ''
    },
    step: 1,
    type: 1,
    currency: {
        symbol: '$',
        rate: 1
    },
    minDays: 0
},
created() {
    //some on create
},
methods: {
    submit() {
        let hasError = false;

        const simpleValidate = (field, message) => {
            if (this.user[field] === '') {
                hasError = true;
                this.errors[field] = message;
            } else this.errors[field] = '';
        };

        const checkBot = (field, message) => {

            var expression = /(https?://(?:www.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}|www.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}|https?://(?:www.|(?!www))[a-zA-Z0-9]+.[^s]{2,}|www.[a-zA-Z0-9]+.[^s]{2,})/gi;
            var regex = new RegExp(expression);

            var expression1 = /[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}b([-a-zA-Z0-9()@:%_+.~#?&//=]*)?/gi;
            var regex1 = new RegExp(expression1);

            if(field == 'email'){

                var expression = /^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})$/i;
                var regex = new RegExp(expression);

                if (!this.user[field].match(regex)) {
                    hasError = true;
                    this.errors[field] = message;
                } else this.errors[field] = '';

            }else{
                if (this.user[field].match(regex) || this.user[field].match(regex1)) {
                    hasError = true;
                    this.errors[field] = message;
                } else this.errors[field] = '';
            }

        };

        simpleValidate('first_name', 'Please enter your first name');
        simpleValidate('email', 'Please enter your email address');

        if(hasError == false){
            checkBot('first_name', 'Please input valid data');
            checkBot('last_name', 'Please input valid data');
            checkBot('phone', 'Please input valid data');
            checkBot('email', 'Please input valid data');
        }

        if (hasError) return;

        const dates = this.selectedDates.sort((a, b) => a.getTime() - b.getTime());

        const currency = Object.keys(rates).find(rate => rates[rate].symbol === this.currency.symbol);

        axios.post(sBaseURI + '/property-requests', {
            property_id: this.unit.property_id,
            dates: {
                start: dates[0],
                end: dates.reverse()[0]
            },
            amount: this.price,
            guests: this.guest,
            user: this.user,
            type: this.type,
            currency : currency
        }).then(res => {
            this.previousStep();
            this.reset();
            this.$refs.datepicker.start = '';
            this.$refs.datepicker.end = '';
            swal({
                'title': "We have received your inquiry.",
                'text': 'An EliteLYFE Travel Designer will contact you shortly.',
                'type': "success",
                'showCancelButton': false,
                'showConfirmButton': true,
                'allowOutsideClick': false,
                'closeOnConfirm': false
            }, function () {
                window.location = res.data;
                swal.disableButtons();
            });

        }).catch(err => {
            console.log(err);
            swal('Something went wrong', 'Please make sure all the fields are properly filled', 'error')
        })
    },
    reset() {
        //reset codes......
    },
    incrementGuest() {
        //increment guest .....
    },
    decrementGuest() {
        // decrement guest .....
    },
    generateDateBetween(start, end) {
        // generateDate codes ...
    }
},
components: {
    Datepicker
}

});

I’m just trying to auto fillup the value of the following

  1. {{ auth->()->user()->first_name }}
  2. {{ auth->()->user()->last_name }}
  3. {{ auth->()->user()->email}}
  4. {{ auth->()->user()->phone }}

to

v-model = user.first_name, user.last_name, user.email, user.phone

If the auth()->user()->.... contains a value, the text fields must be filled automatically using that laravel code. But if not the textfield must be reset to blank.

I’m trying to understand the flow of this vuejs, on how to fill this up.

I removed some unnecessary codes that I know wont help.

UPDATE

Tried the answer below

The problem is my vue codes are separated from blade codes I just used @include to include my vuefile.js to my blade. and when I tried this one

enter image description here

Advertisement

Answer

In my blade file I did this

Using FORM & optional()

    FORM = {
        first_name: '{{ optional(auth()->user())->first_name }}',
        last_name: '{{ optional(auth()->user())->last_name }}',
        email: '{{ optional(auth()->user())->email }}',
        phone: '{{ optional(auth()->user())->phone }}',
    }

and in my vue file js I did this

user: {
  first_name: FORM.first_name,
  last_name: FORM.last_name,
  email: FORM.email,
  phone: FORM.phone
},
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement