【问题标题】:dynamic select options depend on another select option in laravel动态选择选项取决于 laravel 中的另一个选择选项
【发布时间】:2018-08-17 18:15:15
【问题描述】:

我有两个表作为用户和部门。我的部门表有两列作为 id 和标题,我的用户表包含用户信息列和一个 exta 列作为与部门表 id 相关的 dept_id。 I want to create a dropdown select option for departement and when a departement is selected the users which have that related department id should be displayed into another dropdown, how can i do that..?
我正在获取控制器中的所有用户和部门数据并将其发送到查看。

我的控制器是....

    public function index()
    {
      $user = DB::table('users')->get();
      $dept =  DB::table('departments')->get();
      return view('userview', compact('user', 'dept'));
    }

我的看法是……

<select class="form-control" id="department" name="department" >
           @foreach($dept as $dept)
                 <option value="{{ $dept->id }}">{{ $dept->name }}</option>
            @endforeach
 </select>    
 
 
 <select class="form-control" id="user" name="user" >     
      <option>   </option>  
 </select>                                          

【问题讨论】:

    标签: ajax laravel


    【解决方案1】:

    我会使用 Ajax 请求来获取相关用户并填充第二个列表。在UserDepartment 模型中设置关系,如:

    // Department.php
    public function users() {
        return $this->hasMany(User::class);
    }
    
    // User.php
    public function department() {
        return $this->belongsTo(Department::class);
    }
    

    在您的控制器中:

    // DepartmentController.php
    public function index() { 
        return view('userview', [
            'departments' => Department::all()
        ]);
    }
    
    public function users(Request $request, $id) {
        if ($request->ajax()) {
            return response()->json([
                'users' => User::where('dept_id', $id)->get()
            ]);
        }
    }
    

    然后在您的视图中,为第一次选择时的更改事件设置一个事件侦听器:

    <select class="form-control" id="department" name="department" >
         @foreach($departments as $dept) 
            <option value="{{ $dept->id }}">{{ $dept->name }}</option>
         @endforeach 
    </select> 
    
    <select class="form-control" id="user" name="user" ></select>
    
    <script>
        $('#department').on('change', e => {
            $('#user').empty()
            $.ajax({
                url: `/departments/${e.value}/users`,
                success: data => {
                    data.users.forEach(user =>
                        $('#user').append(`<option value="${user.id}">${user.name}</option>`)
                    )
                }
            })
        })
    </script>
    

    【讨论】:

    • 这个路线是什么??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多