Working with arrays and data to populate tables and cross tables using a single Eloquent Model in Vue and Laravel

There are three tables in the database: species, panel, and a cross table called species_panel. The relationship between them is that one panel can contain multiple species, so a one-to-many relationship is used. Data needs to be inserted into the panel table with names and descriptions, while the species table remains unchanged. Additionally, data should be inputted into the cross table.

Issues encountered: - Key added for the panel table but values like name and description showing NULL instead of actual data. - Nothing gets inserted into the cross table.

Need help identifying why the data cannot be inserted as expected. Appreciate any insights or solutions provided. Thank you.

The species table

        +----+-----------------+
        | id | name            |
        +----+-----------------+
        | 1  | Spider Monkey   |
        +----+-----------------+
        | 2  | Squirrel Monkey |
        +----+-----------------+
        | 3  | Vervet Monkey   |
        +----+-----------------+
        | 4  | Dorset Horn     |
        +----+-----------------+
        | 5  | Dorper          |
        +----+-----------------+
        | 6  | Javan Warty Pig |
        +----+-----------------+
        | 7  | Wild Boar       |
        +----+-----------------+

Data structure for other tables:

Panel table

        +----+------+-------------+
        | id | name | description |
        +----+------+-------------+
        | 1  | P001 | Monkeys     |
        +----+------+-------------+
        | 2  | P002 | Sheeps      |
        +----+------+-------------+
        | 3  | P003 | Porks       |
        +----+------+-------------+

species_panel table

        +----+----------+---------+
        | id | panel_id | species |
        +----+----------+---------+
        | 1  | 1        | 1       |
        +----+----------+---------+
        | 2  | 1        | 2       |
        +----+----------+---------+
        | 3  | 1        | 3       |
        +----+----------+---------+
        | 4  | 2        | 4       |
        +----+----------+---------+
        | 5  | 2        | 5       |
        +----+----------+---------+
        | 6  | 3        | 6       |
        +----+----------+---------+
        | 7  | 3        | 7       |
        +----+----------+---------+

Code from species.vue file:

species.vue

            
    (The content inside the code block represents sample code snippet.)

Part of JavaScript code:

Part of JavaScript

           
    (The content inside the code block represents sample code snippet.)

species.php

        
    (The content inside the code block represents sample code snippet.)

panel.php

        
    (The content inside the code block represents sample code snippet.)

index.blade.php

        
    (The content inside the code block represents sample code snippet.)

PanelController.php

          
    (The content inside the code block represents sample code snippet.)

Answer №1

My solution involves utilizing your form to submit data to the database instead of using Axios for HTTP requests. Make sure to name your submitted values accordingly.

 <div class="col-2">
                        <b-form-input v-model="date" class="form-control" type="date" value="getDate" name="date"></b-form-input>
                        <pre class="mt-3 mb-0">{{ date }}</pre>
                    </div>
                    <div class="col-6">
                        <b-form-input v-model="description" placeholder="Enter some text" name="description"></b-form-input>
                        <pre class="mt-3 mb-0">{{ description }}</pre>
                    </div>

In terms of ids, I suggest the following approach:

                        <template slot="name" slot-scope="row" >
                        {{row.item.name}}
                        // Consider using a hidden input field to store ids in an array
                        <input name="species[]" type="hidden" v-model="row.item.id">
                    </template>

This scenario involves a many-to-many relationship where panels can contain different species across various panels. Ensure that Laravel is aware of where to insert the data by referring to your cross table. This may not always be necessary but could be beneficial in certain cases like this one.

    public function species()
{
    return $this->belongsToMany('App\Specie', 'antibody_panels','panel_id','specie_id');
}


     public function panel() {
    return $this->belongsToMany('App\Panel','specie_panels','specie_id','panel_id'); 
}

When dealing with many-to-many relationships, use attach instead of save(). The create method automatically saves data.

        foreach($selectedIds as $selectedid){
        $panel->species()->attach(Specie::find($selectedid));
    } 

I hope this explanation proves helpful.

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

Inner-loop containing a variable limited to the block

I have a structure similar to the example below: new Vue({ el: '#app', data: { tasks: ['task1', 'task2', 'task3'], actions: { 'task1': { name: 'dig', ...

Using AJAX to retrieve Laravel Route results in incorrect URL leading to 404 Error (Not Found)

I am experiencing an issue with my route setup in web.php. Here is the route definition: Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy'); In my blade file, I have a button that triggers a sweetal ...

Using SVG files as properties in React from a data.js file

I have a website where I store my content in a data.js file and pass it to my components using props. Everything is working correctly, except for my .svg files. When I try to display them, they do not appear. However, if I change the extension of the image ...

Is it possible to interact with Java SE jars using JavaScript?

I need to integrate an API that is written in Java with a Client written in JavaScript. Is there any way to use this API, possibly along with other Java-SE JARs, in Webstorm? Any assistance would be greatly appreciated. Thank you! ...

PHP and SQL-based search feature malfunctioning in current implementation

I have been developing a feature that allows users to search for movies in my database. I recently added the ability to limit searches by a specific year, but for some reason, the results are not being filtered correctly. When I run the query directly in M ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

Is there a similar effect in jQuery? This is achieved using prototype

Simply click on the comments link. Observe how the comments smoothly appear, as if sliding down. Also, try clicking on 'hide' and see what happens. ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Packages required for plugins on Npm

I am fairly new to NPM dependencies and I'm currently transitioning from the Ruby world. Working on a Chrome extension utilizing React, in my content.js script, I have the following code at the top: var React = require("react"); var $ = require("jqu ...

Angular is sending a parameter with a null value, which is not supposed to happen

My filtering system used to work well with a code that displayed items of specific status. However, I had to modify it to match a select input requirement. <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button- ...

Error: Compilation was unsuccessful due to module not found. Unable to resolve in ReactJS

As I was wrapping up this task, an unexpected error popped up: Module not found: Can't resolve './components/Post' in ./src/pages/index.js I've tried everything to troubleshoot it but no luck. Here's a rundown of my code snippets ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

How can Vue be utilized to display static data in a modal window?

I have a pair of 'cards' containing the following content: <div class='card'> <span>title one </span> <button @click='open = !open'>show</button> </div> <div class=& ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

Vue.js isn't triggering the 'created' method as expected

I have a main component called App.vue. Within this component, I have defined the created method in my methods object. However, I am noticing that this method is never being executed. <template> <div id="app"> <Header /> <Ad ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...