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

Express throwing module errors

I encountered an issue while attempting to expose a REST service in an electron app using expressJS. Following a tutorial, I added express and @types/express to the project. However, when trying to implement a "get" method and running the build with ng bui ...

NextAuth encountered a CLIENT_FETCH_ERROR error while processing the session callback

Encountering issues while trying to set up nextauth v4. Keep getting this error: Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON d ...

Automatically bypassing git conflicts in package.json: A step-by-step guide

We encounter frequent updates to shared npm packages in our app, resulting in multiple pull requests updating the same package version. Consequently, conflicts arise on GitHub when these pulls are merged into the master branch. Is there a way to automati ...

Capturing content from an HTML node and integrating it into VueJS data

<tasks> @foreach ($task as $tasks) <task>{{ $task->name }} [{{ $task->completed }}]</task> @endforeach </tasks> This snippet shows how I display a list of tasks from the database. Here is my Vue component setu ...

jQuery does not pass data to bootstrap modal

I am currently working with the full calendar feature. Within this framework, I have implemented a modal that allows users to insert new events: <div id="fullCalModal_add_appointment" class="modal fade"> <div class="modal-dialog"> ...

Updating a Rails partial using JSON response from an AJAX post request

I recently implemented an AJAX post request in my backend Rails application to upload a file. Upon successful posting, the response contains a JSON list of files. Now, I face the challenge of reloading the file list on my 'detalhes.html.erb' vie ...

Determine if Param is empty or not within the context of express.js

I am looking to create a table and populate it with all the parameters that are not empty in the parameter list provided below: http://localhost:5002/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="407535732b7008121931190539142 ...

What causes the removeChild function to exhibit distinct behaviors when it comes to list items versus i tags?

It has come to my attention that the removeChild function does not behave in the same way with all elements, particularly when dealing with list items. I am currently using the i tag for icons from frontAwesome and would like to individually remove these i ...

Error: JQuery's on() function is not defined

After modifying the code in the original and changed code boxes, I'm now encountering an Uncaught Type error: Undefined is not a function. Any thoughts on why this might be happening? Thanks Original: $('.comment').click(function(e){ ...

Setting up web pack with flag-icon-css integration

I have successfully set up a webpack project using https://github.com/teroauralinna/webpack-guide. Now, I am looking to integrate https://github.com/lipis/flag-icon-css into my project. To do so, I followed these steps: npm install flag-icon-css --save T ...

Retrieving a function's output in React

Upon attempting to retrieve and log the res.data from my function, I encountered an issue where it returned as undefined. However, when I logged it from within the function, the result appeared normal. const getDefaultState = () => { axios .get ...

Node.js and MongoDB Login Form Integration with Mongoose

I am relatively new to web development and currently working on a simple web page for user login authentication. My goal is to verify user credentials (username & password) on the LoginPage from a mongoose database, and if they are correct, redirect them t ...

Unable to get jQuery waypoints to function on local server

Currently, I am working with jQuery. I downloaded an example shortcut for infinite scroll from jQuery Waypoints and tried to use it. However, when the page reaches the end, the web console displays the following error: XMLHttpRequest cannot load file:// ...

Steps for creating a node.js and ejs file to deploy on 000webhost

I have developed a simple todo-app using node.js and ejs templating. My goal is to host it using 000webhost, a free web-hosting service. I successfully hosted a react app for free on this platform by running "npm run build", which converted the ...

Every time I try to execute npm and npm run watch, I encounter an error message stating: "[webpack-cli] Error: Unknown option '--hide-modules'"

johndoe@johns-mac test-website % npm run watch watch NODE_ENV=development webpack --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js [webpack-cli] Error: Unknown option '--hide-modules' [webpack-cli] Ru ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

When attempting to utilize a global variable in a POST request, it may be found to

My dilemma is that I can successfully access the global variable in other requests such as 'GET', but it becomes undefined when used in a 'POST' request. var dirName; app.post("/addFace", function (req, res) { //create directory con ...

Utilizing jQuery/Ajax to send an ID parameter to a PHP script

This code is where the user interacts. <html> <head> <title></title> <script src="jquery-1.9.1.js"></script> <script src="jquery.form.js"></script> </head> <body> <?php include 'con ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Is it possible to create a translucent glass floating box over HTML elements, similar to the frosted glass effect seen in iOS7?

Creating an overlapping div with a frosted glass effect typically requires using an image background (like ). I am interested in having a floating div (position:fixed) that can apply a frosted glass effect over any content below it, whether it be an image ...