2
votes

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

2
Is your Vue app embedded with blade?Sonu Bamniya
Yes embedded with blade. i can simply show it in other lines of blade. But inside of the textfield laravel code doesnt applyPablo
Yes it won't as you are using v-model which ignore the initial value attributeSonu Bamniya
Please share the vue.js codeChristophe Hubert
I've shared the vuejs codePablo

2 Answers

1
votes

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
},
1
votes

note:editing to remove my misconception and avoid confusion for future readers

When you add the colon before an attribute in Vue (:value=". short for v-bind:value), you're saying that whatever you put in the quotes is valid Javascript. However, you're passing it a literal value: the first name of the person from Laravel.

Because you're using v-model, you would usually insert the initial value your data function rather than in the HTML.

data: {
    units: units,
    guest: 2,
    dates: [],
    selectedDates: [],
    rates: [],
    user: {
        first_name: '(initial value)',

Additionally, be sure that your data option is actually a function which returns a value, as here:

data() {
    return {
        units: units,
        guest: 2,
        dates: [],
        selectedDates: [],
        rates: [],
        user: {
            first_name: '(initial)',
    }
}

edit But because Blade is not available in the .js file with your Vue options, you're left with a decision. My suggestion might ultimately be to create a custom form component which passes through the initial values as props. This would also clean up your .js by separating the form concerns into their own space. If this is the ONLY thing you have going on in #app, then you could pass the initial values as props to the top level component using Blade.

Essentially, you'd have a prop that accepts an object, and then your data function would set the initial values of each variable to that prop object's values.