无法为用户分配角色

时间:2015-12-04 13:28:53

标签: php laravel laravel-5 laravel-5.1

我尝试在我的laravel应用程序上使用spatie(laravel-permission),但我无法为用户分配角色。我面临的错误是

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

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

2 个答案:

答案 0 :(得分:3)

将 Spatie\Permission\Traits\HasRoles trait 添加到您的用户模型:

<?php
    namespace App\Models;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Spatie\Permission\Traits\HasRoles;

    class User extends Authenticatable
    {
        use HasRoles;
        // …
    }

这是一个完整的 Spatie Permissions 示例

答案 1 :(得分:1)

添加特质use HasRoles;

在您的用户模型中