Laravel UserCreationService Used in Controllers and Artisan Command
The first example is from an open-source project called pterodactyl/panel. Here, we have a UserCreationService service, which creates a user using the handle() method.
app/Services/Users/UserCreationService.php:
class UserCreationService
{
public function handle(array $data): User
{
if (array_key_exists('password', $data) && !empty($data['password'])) {
$data['password'] = $this->hasher->make($data['password']);
}
$this->connection->beginTransaction();
if (!isset($data['password']) || empty($data['password'])) {
$generateResetToken = true;
$data['password'] = $this->hasher->make(str_random(30));
}
/** @var \Pterodactyl\Models\User $user */
$user = $this->repository->create(array_merge($data, [
'uuid' => Uuid::uuid4()->toString(),
]), true, true);
if (isset($generateResetToken)) {
$token = $this->passwordBroker->createToken($user);
}
$this->connection->commit();
$user->notify(new AccountCreated($user, $token ?? null));
return $user;
}
}
This service method is called in a few places: two Controllers and one Artisan command.
Reusability is one of the benefits of Services.
app/Http/Controllers/Admin/UserController.php:
// ...
use Pterodactyl\Services\Users\UserCreationService;
class UserController extends Controller
{
public function __construct(
protected AlertsMessageBag $alert,
protected UserCreationService $creationService,
// ...
) {
}
public function store(NewUserFormRequest $request): RedirectResponse
{
$user = $this->creationService->handle($request->normalize());
$this->alert->success($this->translator->get('admin/user.notices.account_created'))->flash();
return redirect()->route('admin.users.view', $user->id);
}
// ...
}
use Pterodactyl\Services\Users\UserCreationService;
class MakeUserCommand extends Command
{
// ...
public function __construct(private UserCreationService $creationService)
{
parent::__construct();
}
public function handle()
{
// ...
$user = $this->creationService->handle(compact('email', 'username', 'name_first', 'name_last', 'password', 'root_admin'));
// ...
}
}
No comments