parabellumkoval / backpack-profile
Implement user profile API & CRUD for backpack
Installs: 198
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 1
Open Issues: 0
pkg:composer/parabellumkoval/backpack-profile
Requires
- php: ^8.2
- backpack/crud: dev-store
- laravel/framework: ^12.0
- laravel/sanctum: ^4.2.0
- laravel/socialite: ^5.23.0
README
Comprehensive user profile, referral, and wallet subsystem for Laravel applications that use Backpack. The package ships ready-to-use CRUD panels, API endpoints, referral triggers, wallet management, reward distribution, withdrawal workflows, and a Sanctum-based authentication layer that can be consumed from SPA or mobile clients.
Feature Overview
- Profile lifecycle: automatic profile creation for new users, profile CRUD for admins, REST endpoints for profile self-service.
- Authentication APIs: email/password registration, login, logout, password reset, email verification, and Socialite OAuth flows (Google/Facebook) with Sanctum personal access tokens.
- Referral engine: multi-level referral tree, reward events, trigger registry, reward ledger, and configurable payout logic.
- Wallet subsystem: balance table, ledger journal, hold/release/capture semantics, CurrencyConverter integration, and withdrawal processing workflow.
- Backpack admin UI: CRUD panels for profiles, referrals, rewards, reward events, wallet ledger, withdrawals, and an analytic dashboard with charts.
- Settings integration: configuration groups exposed through the Backpack Settings package (currencies, withdrawal thresholds, trigger configuration, etc.).
- Extensibility hooks: event listeners on user/profile creation, trigger registry, facades/services for programmatic access, publishable assets for overriding views/routes/config.
Requirements
- PHP 8.2+
- Laravel 12.x
- Backpack 6.x (CRUD + Settings packages)
- Laravel Sanctum 4.2+ for API tokens
- Laravel Socialite 5.23+ for social login (optional)
- Database driver that supports JSON columns (MySQL 5.7+/MariaDB 10.2+/PostgreSQL 9.4+)
Installation
-
Install the package
composer require parabellumkoval/backpack-profile
-
Run migrations
php artisan migrate
This creates core tables such as
ak_profiles,ak_referral_partners,ak_reward_events,ak_rewards,ak_wallet_balances,ak_wallet_ledger, andak_withdrawal_requests. -
(Optional) Publish assets
php artisan vendor:publish --provider="Backpack\Profile\ServiceProvider" --tag=config php artisan vendor:publish --provider="Backpack\Profile\ServiceProvider" --tag=views php artisan vendor:publish --provider="Backpack\Profile\ServiceProvider" --tag=migrations php artisan vendor:publish --provider="Backpack\Profile\ServiceProvider" --tag=routes
- Config is copied to
config/backpack/profile.php. - Views land under
resources/views/vendor/profileandresources/views/vendor/backpack/crud. - Migrations and route stubs are publishable if you need to customize them heavily.
- Config is copied to
-
Configure Backpack Settings (recommended)
Register
Backpack\Profile\app\Settings\ProfileSettingsRegistrarinside your Backpack Settings registrar so that referral, wallet, and withdrawal options become editable from the admin UI.
Quick Start Checklist
| Task | Notes |
|---|---|
Configure config/auth.php guards |
Define a profile guard if you plan to use profile-authenticated routes. |
| Sanctum personal access tokens | Ensure config/sanctum.php is set up; SPA/mobile clients should store bearer tokens securely. |
| Socialite credentials | Set GOOGLE_CLIENT_ID, FACEBOOK_CLIENT_ID, etc., and update config/services.php. |
| Currency converter binding | Bind Backpack\Profile\app\Contracts\CurrencyConverter to your implementation if you need real conversion rates. |
| Settings defaults | Review config/backpack/profile.php (currencies, referral levels, middlewares, withdrawal minimums). |
Database Schema
| Table | Purpose |
|---|---|
ak_profiles |
Profile metadata linked 1:1 with the users table (user_id). Stores locale, sponsor, marketing opt-in flags, referral code, etc. |
ak_referral_partners |
Flattened referral tree with parent relationships for fast traversal. |
ak_reward_events |
Event log for referral trigger executions (pending/processing/processed/failed, reversal support). |
ak_rewards |
Monetary/points rewards issued to beneficiaries (actor or upline) per event. |
ak_wallet_balances |
Snapshot of wallet balances per user and currency. |
ak_wallet_ledger |
Journal of wallet operations (credit/debit/hold/release/capture). |
ak_withdrawal_requests |
Withdrawal workflow records, including FX metadata and admin actions. |
ak_event_counters |
Incremental counters for idempotent trigger execution (subject_type + subject_id). |
Note: legacy code still references columns such as
firstname,lastname, andaddresses. If you rely on these attributes, ensure your schema includes matching columns or adjust the model to align with the published migrations. SeeIMPROVEMENTS.mdfor known inconsistencies.
Configuration Highlights
config/backpack/profile.php drives most behavior:
user_model/profile_model: customize linked Eloquent classes.private_middlewares: middleware stack applied to wallet/withdrawal API routes (defaults to['api', 'auth.api:sanctum']).referral_enabled,referral_levels,referral_commissions: legacy defaults for simple multi-level referral payouts.pointsgroup: toggles the virtual points currency used for wallet operations (key,name,basecurrency backing the point).currencies: list of fiat currencies exposed to the UI; affects select boxes and labels.currency_converter: class implementingBackpack\Profile\app\Contracts\CurrencyConverterused byWithdrawalServiceand referral payouts.withdrawalgroup: enable/disable withdrawals and configure minimum amounts.usersgroup: allow self-registration, require email verification, default role/locale.
Backpack Settings extender (ProfileSettingsRegistrar) mirrors these options in a GUI-friendly manner. Ensure the registrar is invoked by the host application so admins can manage referral triggers, currencies, and withdrawal policies.
Backpack Admin Panels
Once the service provider boots, the following routes are available under the Backpack prefix (default /admin):
profileCRUD (ProfileCrudController): manage user profiles, inspect balances, sponsors, and contact data.referralslist (ReferralsCrudController): list only users with downline referrals, with expandable detail rows.rewardslist (RewardCrudController): read-only grid of issued rewards, filters by beneficiary type, amount, currency.reward-eventslist (RewardEventCrudController): inspect trigger executions, re-process or create reversal events.wallet-ledgerlist (WalletLedgerCrudController): journal of wallet movements.withdrawalslist (WithdrawalRequestCrudController): approve/reject/mark paid, view FX and payout metadata.profile-dashboard(ProfileDashboardController): dashboard with aggregate stats, chart.js graphs for wallet flows, reward volumes, recent referrals, withdrawals.referrals/settings: placeholder for future Settings UI (requires integration with Backpack Settings).
All admin controllers rely on Backpack's CRUD operations, custom columns (e.g., user_card, price, status), and the translation strings shipped under resources/lang/en|ru.
API Surface
Authentication (/api/auth/...)
POST /api/auth/registerPOST /api/auth/loginPOST /api/auth/logout(Sanctum token required)GET /api/auth/me(Sanctum token required)POST /api/auth/password/change(Sanctum token required)POST /api/auth/password/forgotPOST /api/auth/password/resetPOST /api/auth/email/verification-notification(Sanctum token + throttle)POST /api/auth/email/resend(throttle)GET /api/auth/verify-email/{id}/{hash}(signed link)GET /api/auth/oauth/{provider}/urlGET /api/auth/oauth/{provider}/callback
Responses are JSON-only thanks to ForceJsonResponse middleware. The detailed request/response contract and recommended Nuxt/Auth.js integration steps are documented in AUTH_SYSTEM.md.
Profile (/api/profile/...)
GET /api/profile(guardauth:profile) — returnsProfileFullResource.POST /api/profile/update(currently guarded byauth:sanctum) — updates allowed fields after validation.GET /api/profile/referrals(guardauth:profile) — paginated downline list usingProfileTinyResource.
Important: the controller expects an authenticated
profileguard but the update route is wired toauth:sanctum. Align guards in your application or adjust the controller as described inIMPROVEMENTS.md.
Wallet & Withdrawals (/api/wallet/...)
Routes are wrapped in middleware from Settings::get('profile.private_middlewares') (defaults to ['api', 'auth.api:sanctum']).
GET /api/wallet/withdrawalsPOST /api/wallet/withdrawalsPOST /api/wallet/withdrawals/{id}/cancel
WithdrawalService enforces minimum amounts, currency conversion, wallet holds, and ledger bookkeeping. Admin actions (approve/reject/mark paid) are exposed through Backpack routes.
Services & Facades
Backpack\Profile\app\Services\Profile: high-level API for triggering referral events, reversing events, resolving currencies, and retrieving the configured user model.Backpack\Profile\app\Services\ReferralService: core engine that records events, resolves uplines, distributes rewards, and performs reversals.Backpack\Profile\app\Services\WithdrawalService: creates withdrawal requests, handles approval/rejection/capture, interacts with wallet balances.Backpack\Profile\app\Services\WalletService: implementsauthorize,capture,void, and balance retrieval on the wallet ledger.Backpack\Profile\app\Services\TriggerRegistry: registry for referral triggers implementingBackpack\Profile\app\Contracts\ReferralTrigger.Backpack\Profile\app\Services\ProfileFactory: buildsProfileinstances and resolves sponsor linkage based on referral codes.Profilefacade (Backpack\Profile\app\Facades\Profile): shortcut to theProfileservice.- Middleware:
CaptureReferral,ForceJsonResponse,CheckIfAuthenticateProfile.
All services are container-bound in ServiceProvider. You can override bindings in your application service provider if you need to replace behavior.
Events, Notifications, and Observers
- Events:
ProfileCreating,UserCreatingfire during model creation; default listeners populate names and (optionally) referral codes. - Notifications: placeholders for user onboarding (
UserRegistred,ReferralRegistred,ReferralBonus, etc.) and withdrawal completion emails. - Observers:
ProfileObserverandTransactionObserverinclude legacy logic; review them before enabling in production.
Extending the Referral Engine
- Implement
Backpack\Profile\app\Contracts\ReferralTrigger. - Register the trigger alias with
TriggerRegistry::register($alias, $class), typically from a service provider or module boot method. - Configure trigger settings (fixed/percent payouts, actor award, level distribution) via the Backpack Settings UI or
config/settings.php. - Invoke
Profile::trigger($alias, $externalId, $payload, $actorUserId, $opts)whenever an event occurs (e.g., order paid).
Reversals can be created via Profile::reverse(...) or admin UI actions.
Frontend Integration Notes
- Authentication is token-based: clients must send
Authorization: Bearer {token}with Sanctum personal access tokens. - API responses are JSON, validation errors use standard Laravel structure (
errorsarray). - Email verification is optional and controlled by
profile.users.require_email_verification. - Social login flows expect the frontend to call
/oauth/{provider}/url, redirect the browser, and handle/callbackwith optional redirect back to the SPA. AUTH_SYSTEM.mdcontains step-by-step guidance tailored for Nuxt 3 + Auth.js, including error handling and state transitions.
Testing & Development
- The repository currently ships with placeholder tests under
packages/backpack/profile/tests. Update them to use PHPUnit/Pest against the modern package namespace before relying on automated coverage. - Consider adding feature tests that cover registration, login, referral triggers, withdrawal lifecycle, and admin actions to avoid regressions.
Known Gaps & Roadmap
See IMPROVEMENTS.md for a curated backlog of technical debt and missing functionality (schema mismatches, outdated controllers, guard inconsistencies, missing tests, etc.). Addressing those items is recommended before turning the package into a reusable release.
License
The package is open-sourced software licensed under the MIT license.