laravel-admin中省市区select三级联动功能demo
管理员 发布于 4年前   690
laravel-admin中省市区select三级联动功能demo
NewsList调用控制器
<?php
namespace App\Admin\Controllers;
use App\Models\NewsList;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use App\Models\ChinaArea;
class NewsListController extends Controller
{
use HasResourceActions;
/**
* Make a form builder.
* @return Form
*/
protected function form()
{
$form = new Form(new NewsList());
$form->tab('省市区三级联动', function (Form $form) {
$form->select('sheng','省份')->options(
ChinaArea::province()->pluck('name', 'id')
)->load('shi', '/api/china/city');
$form->select('shi','城市')->options(function ($id) {
return ChinaArea::options($id);
})->load('qu', '/api/china/district');
$form->select('qu','区')->options(function ($id) {
return ChinaArea::options($id);
});
})
return $form;
}
}
城市表控制器 (路由过来两个异步加载的接口)
<?php
namespace App\Admin\Controllers\China;
use App\Http\Controllers\Controller;
use App\Models\ChinaArea;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ChinaController extends Controller
{
public function city(Request $request)
{
$provinceId = $request->get('q');
return ChinaArea::city()->where('parent_id', $provinceId)->get(['id', DB::raw('name as text')]);
}
public function district(Request $request)
{
$cityId = $request->get('q');
return ChinaArea::district()->where('parent_id', $cityId)->get(['id', DB::raw('name as text')]);
}
}
城市表结构
CREATE TABLE `Address` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL COMMENT '名称',
`parent_id` int(10) DEFAULT NULL COMMENT '上级ID',
PRIMARY KEY (`id`),
UNIQUE KEY `PK_City` (`id`),
KEY `idx_upid` (`parent_id`),
) ENGINE=InnoDB AUTO_INCREMENT=3743 DEFAULT CHARSET=utf8 COMMENT='城市表';
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ChinaArea extends Model
{
protected $table = 'Address';
public function brothers()
{
return $this->parent->children();
}
public static function options($id)
{
if (! $self = static::find($id)) {
return [];
}
return $self->brothers()->pluck('name', 'id');
}
}
路由
$router->get('api/china/city', 'China\ChinaController@city');
$router->get('api/china/district', 'China\ChinaController@district');
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
该博客于2020-12-7日,后端基于go语言的beego框架开发
前端页面使用Bootstrap可视化布局系统自动生成
是我仿的原来我的TP5框架写的博客,比较粗糙,底下是入口
侯体宗的博客
文章标签
友情链接