简体   繁体   English

更新 laravel 8 中的复选框值(刀片/控制器)

[英]update checkbox value in laravel 8 (blade/ controller )

I'm beginner in laravel and I want to update multiple checkboxes in database .. when I click at update button automatically my inputs show old value also my permissions are checked by old value to update it ..我是 Laravel 的初学者,我想更新数据库中的多个复选框。

relation between user and permission is manytomany .. I have another table named userpermissions who has id_user and id_permission用户和权限之间的关系是 manytomany .. 我有另一个名为 userpermissions 的表,它有 id_user 和 id_permission

this is my update form in ( edit.blade.php)这是我在(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>

and this is my controller where I think have a problem with methods :这是我的控制器,我认为方法有问题:

edit function编辑功能

 public function edit(User $user)
{
    $permissions = Permission::get();
    return view('users.edit', compact('user','permissions'));
}

update function :更新功能:

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 !');
}

and this is my functio store :这是我的功能商店:

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é !');
}

Thanks for advance !感谢提前!

$user->userPermissions()->save($request->input('data'));

One important thing to understand here, is that save() on relation doesn't remove old values from pivot table, it just add more values to it(no distinction check).这里要理解的一件重要事情是,关系上的save()不会从数据透视表中删除旧值,它只是向其中添加更多值(没有区别检查)。 You need something like refresh functionality.您需要诸如刷新功能之类的东西。 Look at attaching\\detaching or sync , second one is more convenient.attaching\\detachingsync ,第二个更方便。

In first case before saving permissions you can do this在保存权限之前的第一种情况下,您可以执行此操作

// remove all old permissions
$user->userPermissions()->detach();
// update them with new one
$user->userPermissions()->attach($request->input('data'));

In second case, which is less verbose then first one you just need to pass and array of permissions to user object.在第二种情况下,比第一种情况更简洁,您只需要将权限数组传递给用户对象。

// this will do both things which we did before
$user->userPermissions()->sync($request->input('data'))

But i encourage you to read the docs and ask questions after ;)但我鼓励您阅读文档并在之后提出问题;)

Another thing which i saw and its not related to the current topic is我看到的另一件事与当前主题无关

$user->userPermissions->pluck('permission_id')->toArray()

you are using lazy load inside of foreach loop which means that on each iteration of the loop you are making a query to the database(N + 1 problem).您在 foreach 循环内使用延迟加载,这意味着在循环的每次迭代中,您都在对数据库进行查询(N + 1 问题)。 You can preload/eager load userPermissions instead of loading them on a fly by declaring with relation in your User model like this您可以通过像这样在 User 模型中声明关系来预加载/急切加载userPermissions 而不是即时加载它们

class User extends Model
{
    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['userPermissions'];
    ...
}

and then in your User object will have userPermissions property which you can compare to permissions.然后在您的User对象中将具有userPermissions属性,您可以将其与权限进行比较。

Hope that you get main idea and info was useful for you!希望你得到主要想法和信息对你有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM