简体   繁体   English

如何使用AJAX保存用户角色?

[英]How do I save users role with AJAX?

I've got 2 models, User, Role and a pivot table. 我有2个模型,用户,角色和数据透视表。 Currently in my controller it shows in checkbox the roles that that user has, how do I do it that it stores wanted role into database? 当前在我的控制器中,它在复选框中显示了该用户具有的角色,如何将所需的角色存储到数据库中呢? How do I write the ajax to save it to the database when I click submit(potvrdi) button? 单击提交(potvrdi)按钮时,如何编写ajax将其保存到数据库? Current ajax(part) that you see here is for displaying data in table. 您在此处看到的当前ajax(部分)用于在表中显示数据。 Script for this function is written in the view 此功能的脚本写在视图中

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,
        );
    }

User 用户

protected $fillable = [
        'name', 'surname', 'email', 'phone', 'password',
    ];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
    public function IsAdmin()
    {
        $IsAdmin = false;
        $IsAdmin = !$this->roles->filter(function ($item) {
            return $item->role == 'Admin';
        })->isEmpty();
        return $IsAdmin;
    }

Role 角色

protected $fillable = [
        'role',
    ];

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

Routes 路线

Route::group(['middleware' => ['web', 'auth']], function () {
    Route::get('/admin', 'PagesController@admin');
    Route::post('/adminForma', 'PagesController@adminForma')->name('adminForma');
    Route::get('/users', 'PagesController@users');
    Route::get('/settings', 'PagesController@settings');
    Route::post('/settings', 'PagesController@settings');
    Route::get('/generateUserTable', 'PagesController@generateUserTable');
    Route::post('/generateUserTable', 'PagesController@generateUserTable');
    Route::get('/live_search/action', 'PagesController@action')->name('live_search.action');
    Route::post('/live_search/action', 'PagesController@action');
    Route::get('/live_search/destroy', 'PagesController@destroy')->name('live_search.destroy');
    Route::post('/live_search/generateUserTable', 'PagesController@generateUserTable');
    Route::get('/live_search/generateUserTable', 'PagesController@generateUserTable')->name('live_search.generateUserTable');
});

In your javascript code, when the user clicks the submit button, get all the checked roles and store their ids in an array. 在您的JavaScript代码中,当用户单击“提交”按钮时,获取所有选中的角色并将其ID存储在数组中。 Then post the data: 然后发布数据:

data = {
  id: user_id,
  roles_ids: roles_ids_array
}

In your controller method, get the user and sync the relationship with the ids. 在您的控制器方法中,获取用户并将其与ID同步。

$user = User::find($request->get('user_id'));
$roles_ids= $request->get('roles_ids');
$user->sync($roles_ids);

Your issue is similar to this one: Laravel attach pivot to table with multiple values 您的问题与此类似: Laravel将枢轴附加到具有多个值的表

暂无
暂无

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

相关问题 登录后如何根据用户在 laravel 中的角色重定向用户 - How do I redirect users after logging in based on their role in laravel 如何在用户浏览器中保存任何字符串? 这有用吗? - How do I save any string in the users browser? is this useful? 如何通过雄辩地与Entrust一起使用Role =&#39;admin&#39;角色的所有用户? - How do I get all Users with Roles where role = 'admin' using eloquent along with Entrust? 如何保存 ajax json 对全局变量的响应以供重用 - How do I save ajax json response to global variable for reuse 在Drupal 6中,如何设置权限以便给定角色可以将角色分配给其他用户,但不能访问权限页面? - in Drupal 6, how do i set permissions so that a given role may assign roles to other users, but not access the permissions page? 如何在PHP的单独文本文件中保存用户通过GET输入发送的文本? - How do I save texts sent by users via GET input in separate text files in php? 如何正确填写表单后如何保存用户数据 - How do I have a form save users data after being incorrectly filled 如何在页面上按角色列出用户? - How to list users by role on page? 如何使用SWF上载为并发用户管理Ajax上载? - How do I manage ajax uploads using SWF Upload for concurrent users? 既然我已经成功设置了users-role_user-roles表并建立了它们之间的连接,那么如何使用Laravel中的角色 - Now that I have successfully set-up a users-role_user-roles tables and connection between them, how do I use the roles in Laravel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM