【问题标题】:How to fill the form checkboxes with checked data from database laravel 5.8如何使用来自数据库 laravel 5.8 的已检查数据填充表单复选框
【发布时间】:2021-01-17 01:29:22
【问题描述】:

我的更新表单有问题,

我使用表单中的复选框创建了具有多个角色的用户,当我需要更新用户时,我将所有数据放入我的更新表单输入字段中,但复选框字段将为空。有没有办法让我用数据库中的数据检查复选框?

这是我的用户模型关系

public function roles()
{
    return $this->belongsToMany(Role::class)->withTimestamps();
}

这是我的榜样关系

public function users()
{
    return $this->belongsToMany(User::class)->withTimestamps();
}

这是我的编辑用户表单

<form action="{{ route('users.update',['user'=>$user]) }}" method="POST">
        @method('PATCH')
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" class="form-control" value="{{ old('name') ?? $user->name }}">
                <span class="text-danger">{{ $errors->first('name') }}</span>
            </div>

            <div class="form-group">
                <label for="email">Email</label>
                <input type="text" name="email" class="form-control" value="{{ old('email') ?? $user->email }}">
                <span class="text-danger">{{ $errors->first('email') }}</span>
            </div>

            <div class="form-group">
                @foreach ($roles as $role)
                <label for="role">{{ $role->name }}</label>
                    <input type="checkbox" name="role[{{$role->id}}]" value="{{ old($role->id) }}"
                    @if(in_array($role->id,old('role',[]) )) checked @endif >
                @endforeach
                <span class="text-danger">{{ $errors->first('role') }}</span>
            </div>

            @csrf
            <button class="btn btn-primary" type="submit">Create</button>
    </form>

这是我的编辑功能

 public function edit(User $user)
    {
        $roles = Role::all();
        return view('users.edit', compact('user', 'roles'));
    }

我只是想知道如何将数据从数据库中提取到我的复选框中并将它们标记为已选中

【问题讨论】:

    标签: laravel eloquent laravel-5.8


    【解决方案1】:

    终于找到答案了

    <div class="form-group">
        @foreach ($roles as $role)
          <label for="role">{{ $role->name }}</label>
    
          <input type="checkbox" name="role[]" value="{{ $role->id }}"
          {{ $role->users->contains($user->id) ? 'checked' : '' }}
          @if(in_array($role->id,old('role',[]))) checked  @endif>
    
       @endforeach
         <span class="text-danger">{{ $errors->first('role') }}</span>
     </div>
    

    【讨论】:

      【解决方案2】:

      我猜你应该用用户角色 id 检查角色 id:

      @if(in_array($role->id, $user->roles->toArray())) checked @endif
      

      【讨论】:

        猜你喜欢
        • 2015-02-13
        • 2014-07-08
        • 2015-09-27
        • 2020-02-27
        • 2021-03-22
        • 1970-01-01
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多