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

时间:2018-11-15 12:45:26

标签: php jquery mysql ajax laravel

我有2个模型,用户,角色和数据透视表。当前在我的控制器中,它在复选框中显示了该用户具有的角色,如何将所需的角色存储到数据库中呢?单击提交(potvrdi)按钮时,如何编写ajax将其保存到数据库?您在此处看到的当前ajax(部分)用于在表中显示数据。该功能的脚本写在视图中

控制器

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

用户

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

角色

protected $fillable = [
        'role',
    ];

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

路线

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

1 个答案:

答案 0 :(得分:0)

在您的JavaScript代码中,当用户单击“提交”按钮时,获取所有选中的角色并将其ID存储在数组中。然后发布数据:

data = {
  id: user_id,
  roles_ids: roles_ids_array
}

在您的控制器方法中,获取用户并将其与ID同步。

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

您的问题与此类似:Laravel attach pivot to table with multiple values