Assign default role to all users except the first user in database LaraveL Spatie

94 Views Asked by At

I'm using Spatie to manage user permissions and roles in a database. I have two roles, Admin and Manager, i want to assign the first user to Admin role and the rest of the users to Manager role.

I tried to assign admin role to the first user like this

 $this->validate($request, [
      'name' => 'required',
      'email' => 'required|email|unique:users,email',
      'password' => 'required|confirmed|min:6',
    ]);

    $input = $request->all();
    $input['password'] = Hash::make($input['password']);

    User::create($input);
    $user = User::first();
    $user->assignRole('Admin')

but i couldn't manage to assign other users to manager role.

1

There are 1 best solutions below

0
yucefbro On

Okey i was able to accomplish what i wanted with this code

 public function addUser(Request $request) {
$this->validate($request, [
  'name' => 'required',
  'email' => 'required|email|unique:users,email',
  'password' => 'required|confirmed|min:6',
]);

$input = $request->all();
$input['password'] = Hash::make($input['password']);

$user = User::create($input);
$user->assignRole('Manager');

$firstUser = User::first();
$firstUser->assignRole('Admin'); 


return response()->json([
  'status' => 200
]);

}