Laravel 5.2二级联动下拉选择框动态加载数据咨询
Hey there! P.S. h-i g,u,y,s ( haha i passed it ) 😄
Alright, let's get this dynamic dropdown working in Laravel. I've tackled this exact scenario plenty of times, so here's a straightforward, step-by-step approach:
First, let's give your dropdowns IDs so we can target them with JavaScript, and clean up the initial markup:
<!-- First dropdown: Device type --> <select id="deviceType"> <option value="laptop">Laptop</option> <option value="tablet">Tablet</option> </select> <!-- Second dropdown: Will be populated dynamically --> <select id="deviceModel"></select>
Assuming you have a database table for your device models (let's say device_models with columns id, name, and type), add this method to your controller (e.g., DeviceController):
use Illuminate\Http\Request; use App\Models\DeviceModel; // Make sure this matches your model name public function getDeviceModels(Request $request) { // Get the selected device type from the request $deviceType = $request->query('type'); // Fetch models matching the type, return as key-value pairs (id => name) $models = DeviceModel::where('type', $deviceType) ->pluck('name', 'id'); // Return as JSON for JavaScript to consume return response()->json($models); }
In your routes/web.php, add a GET route that points to the controller method:
use App\Http\Controllers\DeviceController; Route::get('/device-models', [DeviceController::class, 'getDeviceModels'])->name('device.models');
Now we need to listen for when the first dropdown changes, fetch the corresponding data, and populate the second dropdown. Here's a native JavaScript version (no jQuery needed):
// Wait for the DOM to load document.addEventListener('DOMContentLoaded', function() { const typeSelect = document.getElementById('deviceType'); const modelSelect = document.getElementById('deviceModel'); // Listen for change events on the first dropdown typeSelect.addEventListener('change', function() { const selectedType = this.value; // Clear existing options in the second dropdown modelSelect.innerHTML = ''; // Fetch data from our Laravel endpoint fetch(`/device-models?type=${selectedType}`) .then(response => response.json()) .then(data => { // Loop through the returned data and add options Object.entries(data).forEach(([id, name]) => { const option = document.createElement('option'); option.value = id; option.textContent = name; modelSelect.appendChild(option); }); }) .catch(error => console.error('Oops, something went wrong:', error)); }); // Optional: Trigger the change event on page load to populate initial data typeSelect.dispatchEvent(new Event('change')); });
If you don't need database data (static options)
If your second dropdown options are fixed and don't need to come from the database, you can skip the controller/route part and just handle it all in JavaScript:
document.addEventListener('DOMContentLoaded', function() { const typeSelect = document.getElementById('deviceType'); const modelSelect = document.getElementById('deviceModel'); // Define your static data const deviceModels = { laptop: [ { id: 1, name: 'MacBook Pro 16"' }, { id: 2, name: 'Dell XPS 13' }, { id: 3, name: 'HP Spectre x360' } ], tablet: [ { id: 4, name: 'iPad Pro 12.9"' }, { id: 5, name: 'Samsung Galaxy Tab S8' }, { id: 6, name: 'Google Pixel Tablet' } ] }; typeSelect.addEventListener('change', function() { const selectedType = this.value; modelSelect.innerHTML = ''; // Populate the second dropdown from our static data deviceModels[selectedType].forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name; modelSelect.appendChild(option); }); }); // Trigger initial load typeSelect.dispatchEvent(new Event('change')); });
That should do it! Test it out—when you switch between Laptop and Tablet, the second dropdown will update with the correct options.
内容的提问来源于stack exchange,提问作者Nil the babe

