Storing Numerous Entries in Database - Managing a One-to-Many Connection

I am currently working with Laravel 5.7 and VueJs 2.5.*...

My issue is related to saving data for TicketInvoice and its corresponding TicketInvoiceItems in the database. When I submit the Invoice form, the TicketInvoice data gets stored in the database successfully. However, the TicketInvoiceItems data is being stored as null even if I fill out the form fields. Additionally, I have dynamic fields for TicketInvoiceItems as TicketInvoice has a one-to-many relationship with TicketInvoiceItems. No matter how many rows of fields I add, only one record is being stored in the database, and all items' fields are saved as null.

Below is my store method in TicketInvoiceController:

public function store(Request $request) {
  $ticketInvoiceItems = collect();

  $ticketInvoiceItems->push(new TicketInvoiceItems([
    'ticket_invoice_id' => $request['ticket_invoice_id'],
    'passenger_name' => $request['passenger_name'],
    'ticket_no' => $request['ticket_no'],
    'departure_date' => $request['departure_date'],
    'fares' => $request['fares'],
    'sub_total' => $request['sub_total']
  ]));

  $ticketInvoice = TicketInvoice::create([
    'vendor_id' => $request['vendor_id'],
    'ticket_invoice_no' => $request['ticket_invoice_no'],
    'ticket_invoice_date' => $request['ticket_invoice_date'],
    'ticket_invoice_fares_total' => $request['ticket_invoice_fares_total'],
    'ticket_invoice_grand_total' => $request['ticket_invoice_grand_total'],
  ]);

  $ticketInvoice->ticketInvoiceItems()->saveMany($ticketInvoiceItems);
}

Here is my VueJs code, please review it for any mistakes:

<script>
  export default {
    data() {
      return {
        ticketInvoices: {},
        vendors: null,
        form: new Form({
          id: "",
          vendor_id: "",
          ticket_invoice_no: "",
          ticket_invoice_date: "",
          ticket_invoice_fares_total: "",
          ticket_invoice_grand_total: "",

          ticketInvoiceItems: [{
            id: "",
            ticket_invoice_id: "",
            passenger_name: "",
            ticket_no: "",
            departure_date: "",
            fares: "",
            sub_total: ""
          }]
        })
      };
    },

    methods: {
      createTicketInvoice() {
        this.form
          .post("api/ticket-invoice")
          .then(() => {
            Fire.$emit("RefreshTable");
          })
          .catch(() => {
            swal("Failed!", "There was something wrong.", "warning");
          });
      },

      addItems() {
        this.form.ticketInvoiceItems.push({
          id: "",
          ticket_invoice_id: "",
          passenger_name: "",
          ticket_no: "",
          departure_date: "",
          fares: "",
          sub_total: ""
        });
      },
      removeItems(pos) {
        this.form.ticketInvoiceItems.splice(pos, 1);
      },
    }
  };
</script>

Answer №1

After some investigation, I have discovered a flaw in my data access method...

In the current request, I am not properly accessing the TicketInvoiceItems data. Here is what I am currently doing:

$ticketInvoiceItems - > push(new TicketInvoiceItems([
  'ticket_invoice_id' => $request['ticket_invoice_id'],
  'passenger_name' => $request['passenger_name'],
  'ticket_no' => $request['ticket_no'],
  'departure_date' => $request['departure_date'],
  'fares' => $request['fares'],
  'sub_total' => $request['sub_total']
]));

However, the data sent back from the front end encapsulates all this information within an array of ticketInvoiceItems.

Therefore, I need to adjust my approach and iterate through the array like so:

foreach($request['ticketInvoiceItems'] as $invoiceItem) {
  $ticketInvoiceItems - > push(new TicketInvoiceItems([
    'ticket_invoice_id' => $invoiceItem['ticket_invoice_id'],
    'passenger_name' => $invoiceItem['passenger_name'],
    'ticket_no' => $invoiceItem['ticket_no'],
    'departure_date' => $invoiceItem['departure_date'],
    'fares' => $invoiceItem['fares'],
    'sub_total' => $invoiceItem['sub_total']
  ]));
}

Furthermore, I realize that explicitly setting 'ticket_invoice_id' on the TicketInvoiceItems is unnecessary, as it will be populated by the saveMany() method.

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

Capture every URL path in NuxtJS page navigation

One interesting feature of NuxtJS is the ability to assign routes in a specific way. For instance, by naming a file pages/_book.vue, we can access the route localhost:3000/my-book with the parameter params.book set to "my-book". But what if some books ar ...

How do I identify whether a link from the API is a Nuxt link with :to or :href?

Currently, I am constructing my main menu using data from an API: <b-navbar-nav> <div v-for="result in resultsmenu" :key="result.id"> <span class="hoverlink"> <nuxt-link :to="result. ...

Transform the given string into an array by eliminating all instances of the plus symbol

I need help converting strings into an array by removing the "+" characters. Currently, it is only converting the first element and not all of them. Can you assist me in converting all instances of "+" to "," for every element? let myString = 'jan + f ...

Retrieve the complete HTML content of a webpage, including the values of all input fields

I'm attempting to save the entire webpage as an HTML file, including all previously entered values in input fields. I have already tried this method: $("#content").html(); However, it does not retain the values entered into input fields. $("#conten ...

JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work. I have a button that looks like this: Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is no ...

How to disable items in Vuetify's v-select without having to modify the object

After searching extensively, I have only come across information in the official documentation indicating that v-select's items can be disabled by setting the object's disable property to true as shown below: {text: 'text1', disabled: t ...

Passing a particular object from an array of objects as props in React Native

Suppose you have a static array consisting of 4 objects and the goal is to pass specific data items from the third object in this array. How can this task be accomplished? Let's consider an example: const ENTRIES = [ { name: "John" color: "#fffff" f ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

Discovering the clicked button in a partial view during an onSuccess Ajax call

Within my partial view, I have implemented two buttons: Save and Preview. Both buttons are functioning as expected, with Preview enabling widget preview and Save saving data to the database. However, I am encountering two issues: I am unable to determine ...

Error Encountered While Creating a Polygon Wallet on Fireblocks

After following the instructions from Fireblocks Docs, I successfully created a default wallet named "BTC_TEST" like this: enter image description here. However, when attempting to create a Matic wallet, I encountered an Axios Error. Despite Matic being a ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Sending an object as a prop in React component

I have a function class: function TopicBox({topicName, article1}) { return ( <div className="TopicBox"> <h1>{topicName}</h1> <div className="topicDivider" /> <Ar ...

Discover the power of EJS embedded within HTML attributes!

There are two cases in which I am attempting to use an EJS tag within an HTML attribute. SITUATION 1: <input style="background-image: url(<%= img.URL %>)" /> SITUATION 2: <input onchange="handleCheckboxChange(<%= i ...

Reset the checked state in React JSX to false by using a reset button

After attempting to reset selected radio buttons on this list, it seems like the change I made from {checked} to {user.checked} in input check is causing issues. This modification can be traced back to UserListElement.tsx In an effort to resolve this issu ...

The clash between Kendo UI and jQuery UI

I implemented Kendo UI for the date picker, and I'm looking to incorporate jQuery UI for the autocomplete feature. Upon adding the jQuery auto complete to my code, I encountered the following error: Uncaught TypeError: Cannot read property 'e ...

Generate a random number in PHP with the click of a button

Hello, I have a scenario where I am working with two PHP pages. One page generates random numbers and the other displays them on a page refresh. I would like to find a way to retrieve the current random value by clicking a button instead of refreshing t ...

Guide to generating an array of slot indexes within Vue.js

In the process of developing my personalized carousel, I have chosen to incorporate images using the <img> tag. However, I find that utilizing the Vue method for creating a carousel component offers more flexibility, especially since I intend to inte ...

Adjusting picture dimensions with percentages in canvas and jquery

I'm currently working on a one-page project that involves a canvas where users can click to add or place images randomly. I have made progress with most of the functionality, but as a beginner in jquery and canvas, I am struggling to set a maximum siz ...

Using the click function is not possible once the append function has been applied

After adding TRIGGER DIV A above $(".DIVB").html(data); from an AJAX Response, I am unable to trigger code using $(".TRIGGER DIV A").click(function(). Can anyone clarify why this is happening and suggest a solution or workaround? ...

Get the characteristics of the raphael pie chart

How can I access the attributes of a Raphael pie chart? I'm interested in getting attributes such as stroke color, values (excluding legend), radius, and x/y position. Here's how my pie chart is defined: pie = r.piechart(120, 140, 50, [55, 22] ...