Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions:

public function loadCities(Request $request)
    {
            $provinceId = $request->province_id;
            $cities = Province::where('province_id', $provinceId)->get();

            return response()->json($cities);
    }

Within my create.vue script:

<Multiselect v-model="form.province_id" :options="provinces" valueProp="id" label="name" trackBy="name" :searchable="true" placeholder="Select:" @change="loadCities" />

const cities = ref([]); 

const loadCities = async () => {
    try {
        const response = await router.get(`/apps/address/load-cities/${form.province_id}`);
        cities.value = response.data;
    } catch (error) {
        console.error(error);
    }
}

Regarding my web.id route:

Route::resource('/address', AddressController::class, ['as' => 'apps'])
    ->middleware('permission:address.index|address.create|address.edit|address.delete')
    ->except(['show']);

        Route::get('/address/load-cities/{province_id}', [AddressController::class, 'loadCities'], ['as' => 'apps'])
        ->name('apps.address.loadCities');

However, I am currently encountering an error:

The GET method is not supported for this route. Supported methods: PUT, PATCH, DELETE.

Can I implement dependent dropdowns using inertia router like this? Or is there something missing in my code? Thank you in advance.

Update: When I console.log(form.province_id), it returns null.

Answer №1

To set up the loadCities route in your routes file, use the get method:

 Route::get('/address/load-cities/{province_id}', [AddressController::class, 'loadCities'])->name('apps.address.loadCities');

In your create.vue script, modify the loadCities method to send a GET request to the correct route:

const loadCities = async () => {
    try {
        const response = await router.get(`/address/load-cities/${form.province_id}`); // Make sure to update the route
        cities.value = response.data;
    } catch (error) {
        console.error(error);
    }
}

Ensure that the loadCities function is executed only after selecting the province_id. You can achieve this by monitoring the input event on the Multiselect component.

<Multiselect v-model="form.province_id" :options="provinces" valueProp="id" label="name" trackBy="name" :searchable="true" placeholder="Select:" @input="handleProvinceChange" />

Next, establish the handleProvinceChange method in your Vue component:

const handleProvinceChange = async () => {
    // Verify if the province_id is not null or undefined
    if (form.province_id) {
        await loadCities(); // Invoke the loadCities function
    }
}

Make sure that the loadCities method is defined before the handleProvinceChange method to prevent any reference problems.

In your Vue component, add a watcher for the form.province_id property:

watch: {
  'form.province_id': {
    immediate: true, // Trigger the handler immediately after creating the component
    handler(newProvinceId, oldProvinceId) {
      if (newProvinceId) {
        loadCities(); // Call the loadCities function when province_id changes
      }
    }
  }
}

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

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

What is the best way to arrange a GeoJSON features array based on a specific property value?

I need help sorting a GeoJSON file based on a property and then slicing it to keep only the top 5 features. For instance, I want to take this GeoJSON and arrange it in descending order by the incidents property: ... [ -75.1972382872565 ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

What is the best way to forward a file upload request from a Next.js API to another API?

Trying to crop an image within a Next.js application, then sending it through an API route within the app before reaching an external API endpoint is proving to be a challenge. The process works fine without going through the API route, but once that step ...

Improving nested v-models using computed properties in Vue.js 2 instead of watchers

Consider this simplified VueJS component example: MyForm (parent component) <template lang="pug"> user-component(v-model="apiData.user") </template> <script> export default { name: "MyForm", component ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

What is the process for uploading an image using fetch?

After just starting to learn react, I decided to create a gallery App. However, I am facing an issue when trying to post pictures to the API. Whenever I click on the ADD button, nothing happens except for an error 500 being logged in the console. Below is ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Can LocalStorage be deleted when the application is not running?

Can a specific key in an application's LocalStorage be deleted without having to open the app? I'm considering creating a batch file script for removing a particular key from the app's LocalStorage while the app is not running. The challeng ...

The Vue graphql result is missing the required query attribute

It's puzzling to me why this particular error keeps appearing in the console import gql from 'graphql-tag' // importing gql const getBooksQuery = gql`query // defining the query { books{ name id } } `; export defau ...

Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what m ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Having trouble figuring out the process of mapping and showcasing data within a React application

On my backend server, I have data displaying in the following format: https://i.stack.imgur.com/f0bfN.jpg I am looking to present this data on my frontend react app. I have attempted the following so far- import {useState, useEffect} from 'react&a ...