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

What is the best way to recycle a variable in TypeScript?

I am trying to utilize my variable children for various scenarios: var children = []; if (folderPath == '/') { var children = rootFolder; } else { var children = folder.childs; } However, I keep receiving the following error message ...

An unusual 'GET' request has been made to the '/json/version' endpoint in Express.js

Hey there, I'm facing a challenge with my Express project. For some reason, I keep receiving a 404 error due to a mysterious GET request to '/json/version'. The request seems to bypass the defined routers after adding session data and eventu ...

Is it more beneficial to enhance the style within a vue.js app or to delegate the task to the website that is

Hello there! I am currently working on my first vue.js app and I could use some assistance in deciding on a design strategy. This app will be integrated into a page of a website that is created using Drupal 8. Both the app and the site will utilize bootstr ...

Display a "Loading" image in the gallery before anything else loads

Can a animated loading gif be implemented to load before the gallery images, or would it serve no purpose? The image will be loaded as a background using CSS. <link rel="stylesheet" href="loading.gif" /> Appreciate your help! ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Json object not recognized

I am in the process of developing a basic application where the user can interact with a button to retrieve a JSON object from the database. The object's structure is displayed below. However, the system is failing to recognize the object, resulting i ...

Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://localhost:1883') topic = 'testTopic' client.on('connect', ()=> { client.subscribe(topic) }) client.on(&a ...

Does Three.js lighting adjust according to the bundler used?

Today, I decided to streamline my portfolio project by transitioning it from standard HTML to the Vite bundler for easier dependency management. I simply copied and pasted the existing code, making adjustments to the imports since I had been using relative ...

Organizing information into rows and columns with VueJS

I am currently working on organizing some data and I am looking for a way to present it in a table format with rows and columns using Vue Js. I want the display to look like this: https://i.sstatic.net/uEEbj.jpg The issue I am facing is that my current c ...

Tips for implementing a minimum character length feature in React Material-UI's Autocomplete feature

I am looking to add a 'minimum character length' feature to the autocomplete component in react material-ui. The code snippet below demonstrates what I have so far. constructor(props) { super(props); this.state = { // toggle for ma ...

Merge together JQuery variables

I want to assign a unique number to each JavaScript variable and jQuery element in my code. Take a look at the snippet below: $("#insert1").click(function(){ var collegeId1=$("#collegeId1").val(); $.post('insert.php', {collegeId: colle ...

Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows: obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3}, {'name': 'Sam', ...

Issue with Angular JS orderBy when sorting by numerical fields is not functioning as expected

Within my controller, I implemented code to convert the rank into a Float data type. details.rank = ''; $scope.order = function (predicate) { $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; if (predicate == & ...

Utilizing API calls within a loop using AngularJS

I need to execute a series of APIs in a loop, but I want the second loop to start only after receiving the result from the last API call in the first loop. How can I achieve this? for(var i=0; i<array.length; i++ ) service.getfunction(array[i]).t ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

Implementing failover for queues in Laravel using Beanstalkd

Is there a reliable failover mechanism available for Laravel queues? I recently encountered an issue with my beanstalkd server, resulting in a Pheanstalk_Exception_ConnectionException error in the Laravel (4) queue driver. This prevented new jobs from bei ...

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...

How to display information for generating a chart in a JavaScript file using Laravel?

I have the data for the number of new students registered and online students per month, but I am unsure of how to transfer this data into a JavaScript file in order to create a chart. Below is the JavaScript file: var chart = document.getElementById(&ap ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

Enhancing AngularJS functionality through the integration of jQuery within a TypeScript module

As I try to integrate TypeScript into my codebase, a challenge arises. It seems that when loading jQuery and AngularJS in sequence, AngularJS can inherit functionalities from jQuery. However, when locally importing them in a module, AngularJS fails to exte ...