How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php

public function Itinerary()
{
    return $this->hasMany('App\Itinerary', 'tour_id');
}

and Itinerary.php

public function tour() 
{
    return $this->belongsTo('App\Tour', 'tour_id');
}

The tours table structure is:

id|title|content

The itineraries table structure is:

id|tour_id|day|itinerary

Within the tour-edit.blade.php view, Vue.js is used to dynamically create or add and remove input fields for day and plan.

Code snippet from tour-create.blade.php:

 <div class="row input-margin" id="repeat">
      <div class="col-md-12">
        <div class="row" v-for="row in rows">
          <div class="row">
            <div class="col-md-2">
              <label >Day:</label>
              <input type="text" name="day[]" 
              class="form-control">            
            </div>
            <div class="col-md-8">
              {{ Form::label('itinerary', " Tour itinerary:", ['class' => 'form-label-margin'])}}
              {{ Form::textarea('itinerary[]',null, ['class' => 'form-control','id' => 'itinerary']) }}
            </div> 
            <div class="col-md-2">
              <button class="btn btn-danger" @click.prevent="deleteOption(row)">
              <i class="fa fa-trash"></i></button>
            </div>
          </div>

        </div>
        <div class="row">
          <button class="btn btn-primary add" @click.prevent="addNewOption" >
          <i class="fa fa-plus"></i> Add Field</button>

        </div>
      </div>
    </div> 

The goal is to fill these fields with their respective data. However, all journey details pertaining to a tour are showing up in the itinerary textbox in JSON format.https://i.sstatic.net/2CfQP.png

The Vue.js script being used is:

<script>
var App = new Vue({
el: '#repeat',
data: {
  day:1 ,
  rows:[
  @foreach ($tour->itinerary as $element)
    {day: '{{$element->day}}', plan: '{{$element->plan}}'},
  @endforeach
  ]
},

methods: {

  addNewOption: function() {
    var self = this;
    self.rows.push({"day": "","itinerary":""});
  },

  deleteOption: function(row) {
    var self = this;
    self.rows.splice(row,1);
  },

}
});
</script>

Answer №1

To avoid mixing Blade into JavaScript, the recommended approach is to make an ajax call to an API route that returns data in JSON format, which can then be processed by Vue:

methods:{
  getItinerary(){
     axios.get('api/itinerary').then(response => {
        this.itinerary = response.data;
     })
  }
}

However, this method may require the use of vue-router instead of Laravel web routes, leading us into single-page application (SPA) territory.

If using blade templates is necessary and you prefer not to use Vue for form model binding, take a look at this alternative solution. It demonstrates how to initialize data from your blade templates.

It appears that you are relying on Laravel's form model binding rather than Vue to populate your forms, causing a disconnect between model data and the view. You must choose one approach. If you opt for Vue, utilize v-model to bind data to the form:

Vue will automatically update any changes made in the view. A JSFiddle example has been created assuming you want to continue using Laravel web routes and blade templates: https://jsfiddle.net/w6qhLtnh/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to automatically submit a form when the enter key is pressed

Can anyone help me with a password form issue? I want the enter key to trigger the submit button but it's not working for me. I understand that the password can be viewed in the source code, this is just for practice purposes. <!DOCTYPE html> & ...

Caution: It is not possible to make changes to a component (`App`) during the rendering of another component (`History

I am currently in the process of creating a tic tac toe game, but I'm encountering an error that is preventing me from updating the history. Despite following a tutorial on skillshare.com and mirroring the steps exactly, the error persists. I must men ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

NextJS not maintaining state for current user in Firebase

I'm working on an app utilizing firebase and nextjs. I've set up a login page, but when I try to retrieve the current user, it returns undefined. This issue began a few days ago while working in react native as well - initially, it was related to ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

Tips on invoking a class method within lodash debounce function

Help needed: Issue with TypeError - Expected a function at debounce when calling a class method in the lodash debounce class Foo { bar() { console.log('bar'); } } const foo = new Foo(); _.debounce = debounce(foo.bar(), 300); ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Ways to conceal the lower details in DataGrid Material-UI

Utilizing the DataGrid component from MUI and I'm eager to conceal this element. Any suggestions on how I can achieve this? Thanks! ...

Issues with the creation of an AngularJS table are causing functionality to malfunction

2021 UPDATE: Note: This question was drafted when I was still learning HTML and JS. If you are seeking assistance for an issue, this might not be very useful as my code was messy. Sorry for any inconvenience caused. The question will remain posted in acco ...

javascript: update hidden field if date is past January 15th

Having a bit of trouble with this one after a full day! The form contains a hidden field called 'grant_cycle'. If the form is submitted after January 15th, it should have the value 'Spring, [year]', or if after July 15th, it should be ...

Creating Interactive Graphs with HTML and JavaScript: A Guide to Dynamic Graph Drawing

I am seeking to create a dynamic graph using standard HTML, JavaScript, and jQuery (excluding HTML5). The nodes will be represented by divs with specific contents, connected by lines such as horizontal and vertical. The ability to add and remove nodes dyn ...

What is the method for sending an argument to vuejs filters?

Here is an example of a Vue.js filter: import Vue from 'vue' Vue.filter('truncate', function (value) { return value.substring(0, 10) }) You can use this filter in your HTML like this: <p> {{filename | truncate}} </p> ...

Exploring the potential of Vue.js by incorporating props into styling techniques

I have been working on a component that displays different v-icons and sizes based on the props passed to it. However, I encountered an issue where setting the icon size using styles with one of the props did not change the icon at all. Here is the code ...

Using Handlebars.js to conditionally display data within an object is not functioning as expected

I am attempting to retrieve JSON data value and only display the element if the data is present. However, I am experiencing issues with Handlebar JS. var data = { listBank: [ { "enableSavedCards":"false", "enableAxisAccount":"t ...

Exploring Data in Angular 2: Examining Individual Records

I am currently learning Angular and facing some challenges in structuring my questions regarding what I want to achieve, but here is my query. Within a component, I am retrieving a single user record from a service. My goal is to display this user's ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

My PHP errors and success messages are not being displayed properly after an AJAX success

After making an AJAX call to submit a form, I would like to display either the PHP success message or error message upon completion. This is my current AJAX success function: success: function (data) { resultSuccess = $(data).find("#success") ...

Seeking a proficient Cloud Code specialist skilled in JavaScript, focused on managing installations and channels

My experience with Javascript is limited, but as I work on my application, I realize the necessity of incorporating it into Cloud Code. I have a Parse class called Groups where I store group data including Name, Description, Users, and Requests. Name, Des ...