Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sucoms's avatar

Changing roles on admin panel in checkbox

In presented controller, it's displaying all the users and his attributes(?) such as name, surname, phone and roles. How do I make it that when I select role in checkbox and press "potvrdi"(submit) it submits to database? Do I have to use jquery, ajax? Thank you

Controller

public function action(Request $request) { if ($request->ajax()) { $query = $request->get('query'); if ($query != '') { $data = User::where('surname', 'like', '%'.$query.'%') ->orWhere('name', 'like', '%'.$query.'%') ->orWhere('phone', 'like', '%'.$query.'%') ->orderBy('id') ->get(); } else { $data = User::orderBy('id') ->get(); } return json_encode($this->generateUserTable($data)); } }

public function generateUserTable($data)
{
    $total_row = $data->count();
    $output = "";
    if ($total_row > 0) {
        foreach ($data as $row) {
            $roleNames = '';
            $userRoles = $row->roles()->pluck('id')->toArray();
            // var_dump($userRoles);
            $checked = '';
            foreach (Role::all() as $roles1) {
                if (in_array($roles1->id, $userRoles)) {
                    $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><button type="button" id="potvrdi" class="potvrdi-button btn btn-primary" data-id="'.$row->id.'">
                    <div class="potvrdi">Potvrdi</div>
                    </button></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>
            ';
        }
    } else {
        $output = '
            <tr>
                <td align="center" colspan="5">Nema podataka</td>
            </tr>
        ';
    }
    return array(
        'table_data'  => $output,
        'total_data'  => $total_row,
    );
}
0 likes
0 replies

Please or to participate in this conversation.