无法为用户分配角色 [英] Can't Assign Role to User

查看:36
本文介绍了无法为用户分配角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在laravel应用程序上使用spatie(laravel-permission),但无法为用户分配角色.我遇到的错误是

I tried to use spatie(laravel-permission) on my laravel apps but I can't assign role to the user. The error I facing is

调用未定义的方法Illuminate \ Database \ Query \ Builder :: assignRole()

Call to undefined method Illuminate\Database\Query\Builder::assignRole()

AdminsContoller.php

AdminsContoller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Traits\HasRoles;
class AdminsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::all();

        return view('admin.dashboard', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::whereId($id)->firstOrFail();
        // $user->hasAllRoles(Role::all());
        return view('admin.show', compact('user'));
    }

    public function assignRole($id){
        $user = User::whereId($id)->firstOrFail()->assignRole('Staff');
        redirect('/dashboard');

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
         $user = User::whereId($id)->firstOrFail();
         $user->destroy();

         redirect('/dashboard');
    }
}

推荐答案

添加特征使用HasRoles;

在您的用户模型中

这篇关于无法为用户分配角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆