Laravel /填充复选框

时间:2018-11-15 09:19:55

标签: php laravel if-statement roles

如何用其ID填充每个复选框?愚蠢的事情要坚持下去,但是任何事情都会有所帮助。目前,它正在填充每个复选框。

$total_row = $data->count();
        $output = "";
        if ($total_row > 0) {
            foreach ($data as $row) {
                $roleNames = '';
                $userRoles = $row->roles;
                $checked = '';
                foreach (Role::all() as $roles1) {
                    if (true) {
                        $checked = 'checked="checked"';
                    }
                    $roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
                }
                $output .= '
                    <tr>
                        <td>'.$row->surname.'</td>
                        <td>'.$row->name.'</td>
                        <td>'.$row->phone.'</td>
                        <td>'.$roleNames.'</td>
                        <td>'.$userRoles.'</td>
                        <td><button type="button" id="rowId" class="remove-button btn btn-danger" data-id="'.$row->id.'">
                        <div class="close">&#120;</div>
                        </button></td>
                    </tr>
                ';
            }

编辑: $ userRoles正在与所有用户及其角色一起打印JSON

[{"id":1,"role":"Admin","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":1,"role_id":1}}]
[{"id":2,"role":"Korisnik","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":2,"role_id":2}}]
[{"id":2,"role":"Korisnik","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":3,"role_id":2}}]
[{"id":2,"role":"Korisnik","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":4,"role_id":2}}]
[{"id":1,"role":"Admin","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":9,"role_id":1}},{"id":2,"role":"Korisnik","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":9,"role_id":2}}]
[{"id":2,"role":"Korisnik","created_at":"2018-11-12 10:52:40","updated_at":"2018-11-12 10:52:40","pivot":{"user_id":10,"role_id":2}}]

2 个答案:

答案 0 :(得分:1)

您能否尝试做到这一点,您应该将自己的角色与用户的角色进行比较,而不是将其设置为循环

 foreach (Role::all() as $roles1) {
     if (in_array($roles1->role, (array)$userRoles)) {
        $checked = 'checked="checked"';
     }
     $roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
 }

答案 1 :(得分:0)

尝试检查您的用户角色集合对象是否包含courant角色对象

替换此行

if (true) {

通过

if($userRoles->contains('id', $roles1->id))