Laravel策略(函数App \ Policy的参数太少)

时间:2018-09-29 08:41:28

标签: php laravel

我正在尝试为用户设置政策。但是我不断遇到错误:

  

函数App \ Policies \ UserPolicy :: update()的参数太少,在第481行的/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php中传递了1个参数,正好是2个/resources/views/users/index.blade.php)

     

ErrorException /app/Policies/UserPolicy.php 20

     

位于UserPolicy @ update函数上

当我以super_admin身份登录时,它可以正常工作,但是每当我以其他角色的用户身份登录时,都会引发此错误。

以下是我当前的实现方式:

UserPolicy

class UserPolicy
{
    use HandlesAuthorization;

    public function update(User $user, User $userEdit)  {
        if ($user->id == $userEdit->id) {
            return true;
        }
        return $user->can('update_user');
    }

    public function before($user, $ability) {
        if ($user->hasRole('super_admin')) {
            return true;
        }
    }
}

UsersController

class UsersController extends Controller {

    public function __construct() {
        $this->middleware('auth');
    }

    public function edit(User $user) {
        $this->authorize('update', $user);
        return view('users.edit', [
            'user' => User::with('roles', 'level')->find($user->id),
            'surveys' => \App\Survey::all(),
        ]);
    }

    public function update(UserRequest $request, User $user) {
        $this->authorize('update', $user);
        $request->save();
        session()->flash('success', 'User successfully updated');

        // means user is editing his own profile
        if (auth()->id() == $user->id) {
            return redirect('/dashboard');
        } else {
            return redirect('/users');
        }
    }
}

UserRequest

class UserRequest extends FormRequest {

    public function authorize() {
        return true;
    }

    public function rules() {
        switch ($this->method()) {
            case 'POST':
                return [
                    'name' => 'required|string',
                    'email' => 'required|string|email|max:255|unique:users',
                    'role'  => 'required|exists:roles,id',
                    'level' => 'required|string',
                ];
                break;

            case 'PATCH':
                return [
                    'name' => 'required|string|max:255',
                    'email' => 'required|string|email|max:255|unique:users,email,'.$this->user->id,
                    'role'  => 'sometimes|exists:roles,id',
                    'level' => 'sometimes|string',
                    'password' => 'nullable|sometimes|string|min:6|confirmed'
                ];
                break;

            default:
                break;
        }
    }

    public function save() {
        switch (request()->method()) {
            case 'POST':
                $this->createUser();
                break;

            case 'PATCH':
                $this->updateUser();
                break;

            default:
                break;
        }
    }

    protected function createUser() {
        // random generate password
        $password = str_random(8);

        $user = User::create([
            'name' => request('name'),
            'email' => request('email'),
            'level_id' => request('level'),
            'password' => Hash::make($password),
        ]);
        $user->assignRoleById(request('role'));

        Mail::to($user)->send(new WelcomeMail($user, $password));
    }

    protected function updateUser() {
        $user = User::findOrFail($this->user->id);
        $user->name = request('name');
        $user->email = request('email');

        if (request('password') != '') {
            $user->password = Hash::make(request('password'));
        }

        if (request('level') != '') {
            $user->level_id = request('level');
        }

        $user->update();

        if (request('role') != '') {
            $user->roles()->sync([request('role')]);
        }
    }
}

AuthServiceProvider

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        \App\User::class => \App\Policies\UserPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        foreach ($this->getPermissions() as $permission) {
            Gate::define($permission->name, function($user) use ($permission) {
                return $user->hasRole($permission->roles);
            });
        }
    }

    protected function getPermissions() {
        return Permission::with('roles')->get();
    }
}

2 个答案:

答案 0 :(得分:0)

UserRequest中,调用$user->update();时没有提供任何参数。 update()函数需要一个UserRequest实例以及一个User

尝试一下:$user->update(request()->all(), $user)

编辑: 我只想移动以下内容...

$this->authorize('update', $user);
$request->save();
session()->flash('success', 'User successfully updated');

// means user is editing his own profile
if (auth()->id() == $user->id) {
    return redirect('/dashboard');
} else {
    return redirect('/users');
}

...转到updateUser()函数。

答案 1 :(得分:0)

在我的视图文件中呼叫

@can('update', App\User::class)
    <!-- html code --!>
@endcan

代替

@can('update', $user)
    <!-- html code --!>
@endcan

我没有将用户实例传递给导致错误的函数。