Skip to content

Commit

Permalink
feat: Create interactive artisan command to add user with role
Browse files Browse the repository at this point in the history
  • Loading branch information
nevinsm committed Oct 21, 2024
1 parent 280fe23 commit 60fc862
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
39 changes: 39 additions & 0 deletions app/Console/Commands/AddUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Role;

class AddUser extends Command
{
protected $signature = 'user:add';

protected $description = 'Add a new user with a role';

public function handle()
{
$firstName = $this->ask('Enter the user\'s first name');
$lastName = $this->ask('Enter the user\'s last name');
$email = $this->ask('Enter the user\'s email');

// Fetch available roles
$roles = Role::all()->pluck('label')->toArray();
$role = $this->choice('Select a role for the user', $roles);

// Create the user
$user = User::create([
'first' => $firstName,
'last' => $lastName,
'fullname' => "{$firstName} {$lastName}",
'email' => $email,
'username' => $email,
]);

// Assign the role to the user
$user->assignRole($role); // Ensure you have a method to assign roles

$this->info("User {$firstName} {$lastName} with role {$role} has been created successfully.");
}
}
2 changes: 1 addition & 1 deletion app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Kernel extends ConsoleKernel
* @var array
*/
protected $commands = [
//
\App\Console\Commands\AddUser::class,
];

/**
Expand Down
12 changes: 12 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ public function roles(): BelongsToMany
return $this->belongsToMany(Role::class, 'appuser_role_link', 'uid', 'rid');
}

/**
* Assign a role to the user.
*
* @param string $roleName
* @return void
*/
public function assignRole(string $roleName)
{
$role = Role::where('label', $roleName)->firstOrFail();
$this->roles()->attach($role);
}

/**
* The permissions that belong to the user.
*/
Expand Down

0 comments on commit 60fc862

Please sign in to comment.