Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. Although I am receiving an array of selected options on the controller side, I believe the problem lies within the insert method which is causing the error. I hope my question is clear.

Html:

<form @submit.prevent="addAllocateSites">
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <label class="typo__label">Select Site</label>
                <multiselect v-model="form.selected_sites" :options="options"
                             :multiple="true"
                             :close-on-select="false"
                             :clear-on-select="false" :preserve-search="true"
                             placeholder="Pick Site"
                             name = "selected_sites"
                             label="asset_name" track-by="asset_name"
                             :class="{ 'is-invalid': form.errors.has('selected_sites') }">
                    <template slot="selection" slot-scope="{ values, search, isOpen }"><span
                        class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} Sites selected</span>
                    </template>
                </multiselect>
                <pre class="language-json"><code>{{form.selected_sites}}</code></pre>
            </div>
            <has-error :form="form" field="selected_sites"></has-error>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    </div>
    <br>
</form>

Script:


<script>

import Multiselect from 'vue-multiselect';
import Form from 'vform';

export default {
    components: {
        Multiselect
    },
    data() {
        return {
            form: new Form({
                selected_sites: [],
            }),
            options: []
        }
    },
    methods: {
        getSites() {
            axios.get('api/sites').then(data => {
                this.options = data.data;
                console.log(data.data)
            }, function (data) {
                console.log(data)
            });
        },
        addAllocateSites(){
            this.form.post('api/allocate_sites').then(() => {
                toast.fire({
                    type: 'success',
                    title: 'Sites Allocated Successfully'
                });
            });
        }
    },
    mounted() {
        this.getSites();
        console.log('Component mounted.')
    }
}
</script>

Controller:

public function store(Request $request)
{
    $siteIds = $request->input('selected_sites');

    $validation = Validator::make($request->all(), [
        'selected_sites' => 'required|array',
    ]);

    if ($validation->fails()) {
        return ['Fields required'];
    } else {
        for ($i = 1; $i < count($siteIds); $i++) {
            $sites[] = [
                "site_id" => $siteIds[$i],
                "administrator_id" => Auth::user()->id,
            ];
        }

        $insertData = AllocateSites::insert($sites);

        if ($insertData) {
            return ['Sites Allocated'];
        } else {
            return ['Failed to add data'];
        }
    }
}

Answer №1

After much contemplation, I have uncovered the answer

for ($i = 0; $i < count($siteIds); $i++) {

         $sites[] = [
            "site_id" => $siteIds[$i]['id'],
            "administrator_id" => Auth::user()->id,
             ];
   }

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

Attach a click event handler to a D3 element

Upon loading the page, the nodeClick() method is called without any clicking action. How can I adjust it so that the nodeClick() function is only triggered when I click on the element? Here is the code snippet: var node = svg.selectAll(".node") .on( ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Struggling to implement dynamic background color changes with react hooks and setTimeout

I am struggling to update the colors of 3 HTML divs dynamically, but unfortunately the code below doesn't seem to be effective. function App() { const [redBgColor, setRedBgColor] = useState(null) const [yellowBgColor, setYellowBgColor] = useState( ...

Sending information from one ajax request to anotherORTransferring

Apologies for not including code in this post as I am currently working on a project in a car without internet access. Thankfully, I am using the amazing Stack Exchange app. Currently, I am facing a challenge where I need to work with two separate API cal ...

Creating dynamic input fields and storing user input in real-time using VueJS and VuetifyJS

I am currently working on generating input text fields (v-text-field) and rendering them, which has been successful up to this point. Here is the reference JSON: { "documentAttributes" : { "documentNumber" : "textField" ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...

Selenium is unable to locate certain elements due to the JavaScript page not being fully loaded, causing issues with implicit and explicit wait functions

Confusion reigns as I navigate through this scenario. Working with Selenium 2 in C# and the browser being IE8, our application employs JavaScript for transitioning between panels, though these transitions actually represent different pages while technica ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

Building nested routes in a protected path using react-router version 6

At the moment, I am utilizing react-router-dom version 6.1.1 and I have a private route in use. Typically, within this private route, I include other routes to maintain my Sidebar. This is how my code appears: // App.tsx const RequireAuth: React.FC<P ...

Issues with Kendo Grid showing incomplete data and columns

Having trouble populating a kendo grid with column titles, as some columns appear empty despite having data when checked in the console log. $(function () { $("#uploadBtn").click(function () { var url = window.rootUrl + 'Upload/UploadM ...

During server and browser builds, NextJs encounters a 404 error when trying to access files named _ssgManifest.js and _buildManifest.js. Additionally, the file named _

I recently deployed a NextJs application on a digitalocean droplet running Ubuntu 22.04. "next": "12.2.3", "react": "18.2.0", Encountering a 404 error for the following files: _ssgManifest.js, _buildManifest.js, an ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

Utilizing the require pattern to integrate JavaScript functionality into HTML

Have: project |- consume_script.js |- index.html Need index.html to be like: <html> <head> </head> <body> <script src="consume_script.js"></script> </body> </html> Issue: consume_script ...