How do you get old values when validation fails in laravel and vue

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How do you get old values when validation fails in laravel and vue on this date .

I am using laravel and vue and I want to retrieve the old values when validation fails but I can’t get the old value because of the v-model I’m using in the select box…

<select id="role" name="role" class="form-control @error('role') is-invalid @enderror" v-model="roleType" value="{{old('role')}}">
     <option value="">Choose user role...</option>
     @foreach($roles as $role)
     <option value="{{ $role->name }}" {{ old('role', $role ) == $role->name ? 'selected' : '' }}>{{ $role->display_name }}</option>
      @endforeach
 </select>

My vue script

window.addEventListener('load',function(){
        var app = new Vue({
            el: '#app',
            data:{
                roleType: '',
            },
        });
    });

is there a simple way of achieving this ?

Answer

It’s a bit of mix and match what you’re currently doing with Vue + Blade. I think what you’re looking for is to assign roleType (the Vue variable) with your old input which you get from pageload (so from PHP), because when you use v-model you’re basically assigning the binding to that variable and you cant really assign the value as well.

v-model is basically a shorthand for <some-element :value="myval" @input="myval = $event".

The way I usually solve this, is to have some sort of Form component which is initialized like so:

{{-- some_blade_file.blade.php --}}
<form-component :init-form="@json(old())"></form-component>

Now, your form-component could look something like this:

...
props: {
   initForm: Object,
}, 
mounted() {
   this.some_variable_in_this_component = this.initForm.some_old_value;
},

So the init-form serves as the initial state the Vue component is initialized with. You pass it to the component in your view file (that is where Blade’s @json helper comes in handy; you can also just use {{ json_encode(old()) }}, it works mostly the same).