我是laravel的初学者,我想更新数据库中的多个复选框..当我自动单击更新按钮时,我的输入显示旧值,我的权限也被旧值检查以更新它..
用户和权限之间的关系是多对多的。我有另一个名为 userpermissions 的表,它有 id_user 和 id_permission
这是我在(edit.blade.php)中的更新表格
<form action="{{ url('users/'.$user->id) }}" method="POST">
@csrf
@method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name" required class="form-control" value="{{ $user->name }}">
@error('name')
<ul class="alert"><li class="text-danger">{{ $message }}</li></ul>
@enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="email" required class="form-control" value="{{ $user->email }}">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
@foreach($permissions as $permission)
<input type="checkbox" name="data[]" value="{{ $permission->id }}"
<?php if( in_array($permission->id, $user->userPermissions->pluck('permission_id')->toArray())){ echo 'checked="checked"'; } ?>/>
{{ $permission->name }}
@if($loop->iteration % 3 == 0 ) <br> @else @endif
@endforeach
</div>
</div>
</div>
<div class="text-right mt-4">
<button type="submit" class="btn btn-primary"> Add</button>
</div>
</form>
这是我的控制器,我认为方法有问题:
编辑功能
public function edit(User $user)
{
$permissions = Permission::get();
return view('users.edit', compact('user','permissions'));
}
更新功能:
public function update(UserRequest $request,User $user)
{
$user->update(
$request->only('name', 'email')
);
$user->userPermissions()->save($request->input('data'));
return redirect()->back()->with('status','user updated !');
}
这是我的功能商店:
public function store(UserRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email'=>'required|email',
'password' => 'required|confirmed|min:6',
]);
$user = User::create(
$request->only('name', 'email', 'password')
);
$user->userPermissions()->createMany($request->input('data'));
return redirect()->back()->with('status','Utilisateur ajouté !');
}
感谢提前!