php Laravel Spatie更新用户和同步用户角色

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel Spatie更新用户和同步用户角色相关的知识,希望对你有一定的参考价值。

<?php

namespace App\Http\Requests\V1;

use Dingo\Api\Http\FormRequest;

class UpdateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'sometimes|required',
            'email' => 'sometimes|required|email|unique:users',
            'password' => 'sometimes|required',
            'roles' => 'sometimes|required|array',
            'roles.*' => 'required|exists:roles,name',
        ];
    }

    public function messages()
    {
        return [
            'roles.*.exists' => 'Role not exist',
        ];
    }
}
{
	"name" : "alia",
	"roles":[ "vendor", "administrator"]
}
    public function update(UpdateUserRequest $request, $id)
    {
        $user = $this->user->findOrFailUuid($id);

        $user->fill($request->all());

        $user->save();

        //sync roles

        if ($request->filled('roles')) {

            $roles = [];

            foreach ($request->roles as $role_name) {

                $role = Role::findByName($role_name, 'api');

                if ($role) {
                    $roles[] = $role;
                }
            }

            if (!empty($roles)) {
                $user->syncRoles($roles);
            }
        }

        return new UserResource($user->load($this->user_relationships));
    }

以上是关于php Laravel Spatie更新用户和同步用户角色的主要内容,如果未能解决你的问题,请参考以下文章

php 具有Spatie Peermission包的Laravel Nova用户模型

php WIP:Spatie Laravel许可 - 延长给予和撤销使用给定防护名称的权限

php Laravel Spatie状态获取最新状态

php Laravel上传Spatie Media Libary

php Spatie Laravel Model状态范围具有状态

laravel-用户活动以及模型变动日志-spatie/laravel-activitylog