cyberfly
3/26/2018 - 3:37 AM

Laravel Spatie update user and sync user roles

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