Laravel如何将省市区下拉选项文本而非ID存入数据库
Got it, let's walk through the full steps to ensure you're storing the city name (instead of the ID) in your database. Here's the complete breakdown:
1. Frontend Form Adjustments
First, confirm your Blade form is set up correctly. The province dropdown stays mostly unchanged, but we’ll ensure the city dropdown is ready to pass the city name value:
<div class="form-group"> {{ Form::label('state', 'State') }} <select name="state" id="state" class="form-control"> <option value="">{{ __('Select Province') }}</option> @foreach ($state->data as $info) <option value="{{ $info->province_id }}">{{ $info->province }}</option> @endforeach </select> </div> <div class="form-group"> {{ Form::label('city', 'City') }} <select class="form-control" name="city" id="city"> <option value="">{{ __('Select City') }}</option> </select> </div>
2. Updated JavaScript for City Dropdown
You already modified the value attribute to city_name, but let’s refine the JS to ensure it’s properly populating options with the correct text and value:
<!-- find cities --> <script type="text/javascript"> $(document).ready(function() { $('select[name="state"]').on('change', function() { var provinceID = $(this).val(); if(provinceID) { $.ajax({ url: '{{ url('admin/getcitylistshipping') }}/' + encodeURI(provinceID), type: "GET", dataType: "json", success:function(data) { $('select[name="city"]').empty().append("<option value='' selected>{{ __('Select City') }}</option>"); $.each(data.data, function(key, value) { // Set option value to city_name, display text as "type - city_name" $('select[name="city"]').append('<option value="'+ value['city_name'] +'">'+ value['type'] + ' - ' + value['city_name'] +'</option>'); }); } }); } else { $('select[name="city"]').empty().append("<option value='' selected>{{ __('Select City') }}</option>"); } }); }); </script>
3. Backend Route Setup
Add the route for fetching cities in your routes/web.php (or admin-specific route file if you’re using a prefix):
Route::get('admin/getcitylistshipping/{provinceID}', [YourShippingController::class, 'getCityListShipping']);
Replace YourShippingController::class with your actual controller name.
4. Controller Method for Fetching Cities
In your controller, make sure the getCityListShipping method returns the necessary city data (including city_name and type):
public function getCityListShipping($provinceID) { // Fetch cities matching the selected province ID $cities = City::where('province_id', $provinceID)->get(['city_name', 'type']); // Return data as JSON return response()->json(['data' => $cities]); }
Adjust the City model and query to match your actual database structure.
5. Prepare Database & Model
- Database Field: Ensure the column storing the city (e.g., in
addressesororderstable) is aVARCHARtype (since we’re storing a string name, not an integer ID). For example, setcity VARCHAR(255)in your migration. - Model Fillable: Update your target model (e.g.,
Address.php) to includecityin the$fillablearray for mass assignment:
class Address extends Model { protected $fillable = [ // Other fields... 'state', 'city' ]; }
6. Handle Form Submission
In your form submission controller method, you can now directly save the city value from the request (it’s the city name, not ID):
public function store(Request $request) { // Validate the request $request->validate([ 'state' => 'required', 'city' => 'required' ]); // Create or update the record Address::create([ // Other fields... 'state' => $request->state, // This is still province ID; adjust if you want to store province name too 'city' => $request->city // Now stores the selected city name ]); // Redirect with success message return redirect()->back()->with('success', 'Record saved successfully'); }
Note: If you also want to store the province name instead of ID, modify the province dropdown’s value to $info->province and update the backend logic accordingly.
7. Test the Flow
- Select a province and confirm the city dropdown populates with options where the
valueis the city name. - Submit the form and check your database to verify the city name is stored correctly.
内容的提问来源于stack exchange,提问作者mafortis

