Backend Development 10 min read

Implementing Automatic Address Recognition in Laravel with jQuery

This article demonstrates how to build an automatic address recognition feature for user input by combining Laravel backend controllers, repository services, and jQuery AJAX calls to parse, validate, and populate name, mobile, and detailed address fields.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing Automatic Address Recognition in Laravel with jQuery

Automatic address recognition is widely used in e‑commerce to fill name, phone number and address fields; the following example shows a simple implementation for a Laravel admin panel.

/** @var UserRepository */ private $userRepository; public function __construct(UsersRepository $userRepo) { $this->userRepository = $userRepo; }

The controller receives the raw string $discernDel from the front end, starts a database transaction, calls the repository method getDiscern , and returns a JSON response containing the parsed components.

/** * Function: 地址识别 * Author: cyw0413 * @param Request $request * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory|\Symfony\Component\HttpFoundation\Response */ public function getDiscern(Request $request) { $discernDel = $request->input('discernDel'); try { DB::beginTransaction(); $address = $this->userRepository->getDiscern($discernDel); DB::commit(); } catch (\Exception $e) { DB::rollBack(); $msg = "信息提示:" . $e->getMessage() . ",行:" . $e->getLine(); return response(['code' => 0, 'msg' => $msg]); } return response(['code' => 1, 'msg' => $address]); // 地址识别完成 }

The repository parses the input string, which must follow the pattern name[mobile]address , validates each part, and then calls helper methods to match the province, city and district against an address database.

/** * Function: 识别地址 * Author: cyw0413 */ public function getDiscern($discernDel) { if (empty($discernDel)) { throw new \Exception("请传入要识别的地址"); } $discernDel_left = explode('[', $discernDel); if (!isset($discernDel_left[1])) { throw new \Exception("你填写的地址规则错误,手机号码应该用[]"); } $discernDel_right = explode(']', $discernDel_left[1]); if (!isset($discernDel_right[1]) || empty($discernDel_right[1])) { throw new \Exception("你填写的地址规则错误,手机号码应该用[]"); } $name = $discernDel_left[0]; if (empty($name)) { throw new \Exception("你填写的姓名有误!"); } $mobile = $discernDel_right[0]; if (empty($mobile) || checkMobile($mobile) == 0) { throw new \Exception("你填写的手机号码格式有误!"); } $address = trim($discernDel_right[1]); if (empty($address)) { throw new \Exception("你填写的地址不能为空"); } $var_address = $this->getAddressArrar($address); $var_address['name'] = $name; $var_address['mobile'] = $mobile; return $var_address; }

Address matching is performed by getAddressArrar , which recursively searches the region hierarchy (province → city → district) and handles special cases such as municipalities without a second‑level city.

/** * Function: 地址的处理 * Author: cyw0413 */ function getAddressArrar($address) { $regions = $this->getRegions(); $province = $city = $district = []; $province = $this->checkAddress($address, $regions); if ($province) { // ...省份、城市、地区的进一步匹配逻辑 ... } else { throw new \Exception("省份没填写,请检查"); } return $this->getAddressInfo($address, $province, $city, $district); }

The front‑end provides a textarea for the raw address and a button that triggers the jQuery getDiscern() function.

<div class="form-group"> {!! Form::label('discern','自动识别地址:',['class'=>'control-label col-sm-2']) !!} <div class="col-sm-5"> {!! Form::textarea('discern','',[ 'class'=>'form-textarea form-control form-discern','rows'=>3]) !!} </div> <div class="col-sm-3" style="height: 75px;"> <button type="button" class="btn btn-info btn-sm discern" onclick="getDiscern();">提交识别</button> <small class="ruleGet" style="color: #676a74;">*查看模板</small> </div> </div>

The jQuery function collects the textarea value, validates it, sends it via AJAX to the Laravel route, and on success fills the corresponding input fields and triggers change events for province, city and area selectors.

/** * 地址识别 * @returns {boolean} */ function getDiscern() { var discernDel = $(".form-discern").val(); if (!discernDel) { alert("请输入要识别的地址"); return false; } $.ajax({ type: 'POST', url: "{!! route('admin.user.getDiscern') !!}", data: { '_token': csrf_token(), 'discernDel': discernDel }, dataType: 'json', timeout: 50000, success: function(res) { if (res.code == 1) { $("input[name='addr[linkman]']").val(res.msg.name); $("input[name='user_name']").val(res.msg.mobile); $("input[name='addr[address]']").val(res.msg.info); $('#province').val(res.msg.province).trigger('change'); $('#city').val(res.msg.city).trigger('change'); $('#area').val(res.msg.district).trigger('change'); $(".form-discern").val(""); } else { alert(res.msg); } } }); }

Overall, the solution shows a clear separation of concerns: the Laravel controller handles request validation and business logic, the repository encapsulates address parsing, and the front‑end uses jQuery to interact with the API, making the whole process easy to understand and extend.

ValidationPHPRepositoryAJAXLaraveljQueryaddress parsing
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.