PHP code example of litepie / users
1. Go to this page and download the library: Download litepie/users library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
litepie / users example snippets
use Litepie\Users\Facades\Users;
// Create a new user
$user = Users::createUser([
'name' => 'John Doe',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'regular',
]);
// The user is automatically:
// - Assigned a unique ID
// - Given default permissions
// - Added to your database
// - Ready to authenticate
return [
/*
|--------------------------------------------------------------------------
| User Model Configuration
|--------------------------------------------------------------------------
*/
'models' => [
'user' => \Litepie\Users\Models\User::class,
'profile' => \Litepie\Users\Models\UserProfile::class,
'session' => \Litepie\Users\Models\UserSession::class,
],
/*
|--------------------------------------------------------------------------
| User Types Configuration
|--------------------------------------------------------------------------
| Define different user types with their specific behaviors and workflows
*/
'user_types' => [
'regular' => [
'class' => \Litepie\Users\UserTypes\RegularUserType::class,
'label' => 'Regular User',
'description' => 'Standard application user',
'registration_enabled' => true,
'auto_activate' => false,
'default_role' => 'user',
'workflow' => 'user_registration',
],
'client' => [
'class' => \Litepie\Users\UserTypes\ClientUserType::class,
'label' => 'Client',
'description' => 'Business client user',
'registration_enabled' => true,
'auto_activate' => false,
'default_role' => 'client',
'workflow' => 'client_registration',
],
'admin' => [
'class' => \Litepie\Users\UserTypes\AdminUserType::class,
'label' => 'Administrator',
'description' => 'System administrator',
'registration_enabled' => false,
'auto_activate' => true,
'default_role' => 'admin',
'workflow' => 'admin_setup',
],
'system' => [
'class' => \Litepie\Users\UserTypes\SystemUserType::class,
'label' => 'System User',
'description' => 'Automated system user',
'registration_enabled' => false,
'auto_activate' => true,
'default_role' => 'system',
'workflow' => null,
],
],
/*
|--------------------------------------------------------------------------
| Registration Settings
|--------------------------------------------------------------------------
*/
'registration' => [
'enabled' => env('USERS_REGISTRATION_ENABLED', true),
'auto_activate' => env('USERS_AUTO_ACTIVATE', false),
'auto_login' => env('USERS_AUTO_LOGIN', false),
'allowed_types' => ['regular', 'client'],
' 'audit_enabled' => true,
'log_sensitive_data' => false,
'encrypt_personal_data' => env('USERS_ENCRYPT_PII', false),
'anonymize_after_deletion' => true,
'gdpr_compliance' => [
'enabled' => true,
'retention_days' => 2555, // 7 years
'auto_delete_inactive' => false,
],
'suspicious_activity_detection' => [
'enabled' => true,
'unusual_login_location' => true,
'unusual_login_time' => true,
'multiple_failed_attempts' => true,
'account_enumeration' => true,
],
],
/*
|--------------------------------------------------------------------------
| File Management
|--------------------------------------------------------------------------
*/
'files' => [
'avatars' => [
'enabled' => true,
'disk' => 'public',
'path' => 'avatars',
'max_size' => 2048, // KB
'allowed_types' => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
'variants' => [
'thumb' => ['width' => 64, 'height' => 64],
'medium' => ['width' => 256, 'height' => 256],
'large' => ['width' => 512, 'height' => 512],
],
],
'attachments' => [
'enabled' => true,
'disk' => 'private',
'path' => 'user-documents',
'max_size' => 10240, // KB
'allowed_types' => ['pdf', 'doc', 'docx', 'txt', 'jpg', 'png'],
],
],
/*
|--------------------------------------------------------------------------
| API Configuration
|--------------------------------------------------------------------------
*/
'api' => [
'enabled' => true,
'prefix' => 'api/users',
'middleware' => ['api', 'auth:sanctum'],
'rate_limiting' => [
'enabled' => true,
'max_requests' => 60,
'per_minutes' => 1,
],
'documentation' => [
'enabled' => env('API_DOCS_ENABLED', true),
'path' => '/docs/users',
],
],
/*
|--------------------------------------------------------------------------
| Workflow Configuration
|--------------------------------------------------------------------------
*/
'workflows' => [
'user_registration' => \Litepie\Users\Workflows\UserRegistrationWorkflow::class,
'client_registration' => \Litepie\Users\Workflows\ClientRegistrationWorkflow::class,
'admin_setup' => \Litepie\Users\Workflows\AdminSetupWorkflow::class,
'password_reset' => \Litepie\Users\Workflows\PasswordResetWorkflow::class,
'account_verification' => \Litepie\Users\Workflows\AccountVerificationWorkflow::class,
],
/*
|--------------------------------------------------------------------------
| Notification Configuration
|--------------------------------------------------------------------------
*/
'notifications' => [
'channels' => ['mail', 'database'],
'welcome_email' => true,
'verification_email' => true,
'password_reset_email' => true,
'security_alerts' => true,
'login_notifications' => false,
'templates' => [
'welcome' => \Litepie\Users\Notifications\WelcomeUser::class,
'verification' => \Litepie\Users\Notifications\VerifyEmail::class,
'password_reset' => \Litepie\Users\Notifications\ResetPassword::class,
],
],
/*
|--------------------------------------------------------------------------
| Performance Configuration
|--------------------------------------------------------------------------
*/
'performance' => [
'cache_user_data' => true,
'cache_duration' => 3600, // seconds
'queue_operations' => [
'bulk_operations' => true,
'email_sending' => true,
'file_processing' => true,
],
'pagination' => [
'default_per_page' => 15,
'max_per_page' => 100,
],
],
];
use Litepie\Users\Facades\Users;
use Litepie\Users\Models\User;
// Create a basic user
$user = Users::createUser([
'name' => 'John Doe',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'regular',
]);
// Create a user with profile data
$user = Users::createUser([
'name' => 'Jane Smith',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'client',
'profile' => [
'first_name' => 'Jane',
'last_name' => 'Smith',
'phone' => '+1-555-123-4567',
'company' => 'Acme Corporation',
'job_title' => 'CEO',
'bio' => 'Experienced business leader...',
'website' => 'https://acme.com',
'address_line_1' => '123 Business Ave',
'city' => 'New York',
'state' => 'NY',
'postal_code' => '10001',
'country' => 'US',
],
'preferences' => [
'theme' => 'dark',
'language' => 'en',
'timezone' => 'America/New_York',
'notifications' => [
'email' => true,
'push' => false,
'sms' => true,
],
],
]);
// Create user via workflow (recommended)
$workflow = Users::startWorkflow('user_registration', [
'name' => 'Bob Wilson',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'regular',
]);
// Create user with custom validation
$user = Users::createUser([
'name' => 'Alice Cooper',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'admin',
], [
'skip_email_verification' => true,
'auto_activate' => true,
'send_welcome_email' => false,
]);
// Update basic user information
$user = Users::updateUser($user, [
'name' => 'John Smith',
'status' => 'active',
]);
// Update user profile
$user = Users::updateProfile($user, [
'first_name' => 'John',
'last_name' => 'Smith',
'phone' => '+1-555-987-6543',
'bio' => 'Updated bio information...',
]);
// Update user preferences
$user = Users::updatePreferences($user, [
'theme' => 'light',
'notifications.email' => false,
'language' => 'es',
]);
// Bulk update users
Users::bulkUpdate([1, 2, 3], [
'status' => 'active',
'updated_by' => auth()->id(),
]);
// Activate a user
Users::activateUser($user, [
'reason' => 'Email verified',
'activated_by' => auth()->id(),
]);
// Deactivate a user
Users::deactivateUser($user, [
'reason' => 'User requested account closure',
'deactivated_by' => auth()->id(),
]);
// Suspend a user
Users::suspendUser($user, [
'reason' => 'Policy violation',
'suspended_by' => auth()->id(),
'suspension_duration' => now()->addDays(7),
]);
// Ban a user permanently
Users::banUser($user, [
'reason' => 'Repeated policy violations',
'banned_by' => auth()->id(),
]);
// Check user status
if ($user->isActive()) {
// User can perform actions
}
if ($user->isSuspended()) {
// Show suspension message
}
// Login with email and password
$result = Users::attemptLogin([
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'remember' => true,
]);
if ($result['success']) {
$user = $result['user'];
$token = $result['token']; // For API authentication
} else {
$errors = $result['errors'];
}
// Login with additional security checks
$result = Users::attemptLogin([
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'device_name' => 'iPhone 15 Pro',
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
// Logout
Users::logout($user);
// Logout from all devices
Users::logoutFromAllDevices($user);
// Enable 2FA for a user
$twoFactorData = Users::enableTwoFactorAuth($user, [
'method' => 'totp', // totp, sms, email
'phone' => '+1-555-123-4567', // Required for SMS
]);
// The response de);
// Verify 2FA during login
$isValid = Users::verifyTwoFactorCode($user, $code, [
'method' => 'totp',
'remember_device' => true,
]);
// Disable 2FA
Users::disableTwoFactorAuth($user, [
'verification_method' => 'password',
'verification_value' => 'current_password',
]);
// Get active sessions
$sessions = Users::getActiveSessions($user);
// Revoke specific session
Users::revokeSession($user, $sessionId);
// Revoke all other sessions
Users::revokeOtherSessions($user, $currentSessionId);
// Check concurrent session limit
if (Users::exceedsConcurrentSessionLimit($user)) {
// Handle too many sessions
}
// Assign role to user
Users::assignRole($user, 'manager', [
'expires_at' => now()->addMonths(6),
'scope' => 'tenant',
'assigned_by' => auth()->id(),
]);
// Assign multiple roles
Users::assignRoles($user, ['editor', 'reviewer']);
// Remove role
Users::removeRole($user, 'manager');
// Sync roles (removes all other roles)
Users::syncRoles($user, ['admin', 'supervisor']);
// Check if user has role
if ($user->hasRole('admin')) {
// User is an admin
}
// Check if user has any of these roles
if ($user->hasAnyRole(['admin', 'manager'])) {
// User has admin or manager role
}
// Get user roles
$roles = $user->getRoleNames();
// Grant permission directly to user
Users::grantPermission($user, 'edit_posts');
// Grant multiple permissions
Users::grantPermissions($user, ['edit_posts', 'delete_posts']);
// Revoke permission
Users::revokePermission($user, 'edit_posts');
// Check permissions
if ($user->can('edit_posts')) {
// User can edit posts
}
// Check with Laravel's authorization
if (auth()->user()->can('view', $post)) {
// User can view this specific post
}
// Get all user permissions
$permissions = $user->getAllPermissions();
// Get direct permissions (not via roles)
$directPermissions = $user->getDirectPermissions();
// Get permissions via roles
$rolePermissions = $user->getPermissionsViaRoles();
// Upload avatar
$avatar = Users::uploadAvatar($user, $request->file('avatar'), [
'crop' => [
'x' => 10,
'y' => 10,
'width' => 200,
'height' => 200,
],
'generate_variants' => true,
]);
// Get avatar URL
$avatarUrl = $user->avatar_url;
// Get specific variant
$thumbUrl = $user->getAvatarUrl('thumb');
$largeUrl = $user->getAvatarUrl('large');
// Remove avatar
Users::removeAvatar($user);
// Attach file to user
$attachment = Users::attachFile($user, $request->file('document'), [
'title' => 'Driver License',
'category' => 'identity',
'description' => 'User identification document',
'metadata' => [
'document_type' => 'drivers_license',
'expiry_date' => '2025-12-31',
],
]);
// Get user files
$files = $user->getFiles();
$identityFiles = $user->getFiles('identity');
// Remove file
Users::removeFile($user, $fileId);
use Litepie\Users\Workflows\UserRegistrationWorkflow;
// Start a workflow
$workflow = Users::startWorkflow('user_registration', [
'name' => 'John Doe',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
'user_type' => 'client',
]);
// Check workflow status
$status = $workflow->getStatus();
$currentStep = $workflow->getCurrentStep();
$progress = $workflow->getProgress(); // Percentage complete
// Advance workflow manually (if needed)
$workflow->advance([
'admin_approval' => true,
'approved_by' => auth()->id(),
'notes' => 'Approved after document verification',
]);
// Get workflow history
$history = $workflow->getHistory();
use Litepie\Flow\Workflow;
use Litepie\Users\Events\UserRegistered;
class CustomClientOnboardingWorkflow extends Workflow
{
protected $steps = [
'validate_business_info',
'verify_business_license',
'setup_payment_methods',
'admin_approval',
'send_welcome_package',
'schedule_onboarding_call',
];
public function validateBusinessInfo($data)
{
// Custom validation logic
$validator = validator($data, [
'business_name' => ''],
]);
if (!$result['valid']) {
return $this->fail('Business license verification failed');
}
return $this->advance([
'verification_id' => $result['id'],
'verified_at' => now(),
]);
}
protected function onWorkflowCompleted($data)
{
// Send notifications, create records, etc.
event(new UserRegistered($data['user']));
// Setup user dashboard
$this->setupClientDashboard($data['user']);
}
}
// Get comprehensive user statistics
$stats = Users::getStatistics();
/*
Returns:
[
'total_users' => 1250,
'active_users' => 1100,
'pending_users' => 75,
'suspended_users' => 25,
'new_registrations_today' => 12,
'new_registrations_this_week' => 85,
'new_registrations_this_month' => 340,
'user_types' => [
'regular' => 950,
'client' => 250,
'admin' => 50,
],
'login_stats' => [
'today' => 450,
'this_week' => 2800,
'this_month' => 12500,
],
]
*/
// Registration trends
$trends = Users::getRegistrationTrends([
'period' => '30days',
'group_by' => 'day',
]);
// Activity statistics
$activityStats = Users::getActivityStatistics([
'period' => '7days',
'
// Create custom reports
$report = Users::createReport([
'name' => 'Monthly User Acquisition',
'type' => 'user_registration',
'filters' => [
'date_range' => [
'start' => now()->startOfMonth(),
'end' => now()->endOfMonth(),
],
'user_types' => ['regular', 'client'],
'status' => ['active', 'pending'],
],
'group_by' => 'day',
'metrics' => ['count', 'conversion_rate'],
]);
// Export report
$export = Users::exportReport($report, [
'format' => 'csv', // csv, excel, json, pdf
'
// Advanced user search
$users = Users::search([
'query' => 'john doe',
'filters' => [
'user_type' => ['regular', 'client'],
'status' => 'active',
'created_at' => [
'start' => now()->subDays(30),
'end' => now(),
],
'has_role' => 'manager',
'has_permission' => 'edit_posts',
'profile.company' => 'Acme Corp',
'profile.city' => 'New York',
],
'sort' => [
'field' => 'created_at',
'direction' => 'desc',
],
'with' => ['profile', 'roles', 'permissions'],
'per_page' => 25,
]);
// Search with complex conditions
$users = Users::searchWhere(function ($query) {
$query->where('status', 'active')
->where(function ($q) {
$q->where('name', 'like', '%john%')
->orWhere('email', 'like', '%john%');
})
->whereHas('profile', function ($q) {
$q->where('company', 'like', '%tech%');
})
->whereHas('roles', function ($q) {
$q->whereIn('name', ['admin', 'manager']);
});
});
// All operations are automatically scoped to the current tenant
$users = User::all(); // Only returns users for current tenant
// Manually set tenant context
tenant()->setId(123);
$tenantUsers = User::all();
// Cross-tenant operations (admin only)
$allUsers = User::withoutTenantScope()->get();
// Create tenant-specific user
$user = tenant()->users()->create([
'name' => 'Tenant User',
'email' => '[email protected] ',
'password' => bcrypt('password'),
]);
// config/users.php
'tenancy' => [
'enabled' => true,
'tenant_model' => \App\Models\Tenant::class,
'isolation_level' => 'database', // database, schema, application
'auto_switch_tenant' => true,
'cache_tenant_data' => true,
'tenant_column' => 'tenant_id',
'middleware' => [
'web' => ['tenant.resolve'],
'api' => ['tenant.resolve', 'tenant.verify'],
],
],
use Litepie\Users\Facades\TenantManager;
// Create tenant with users
$tenant = TenantManager::createTenant([
'name' => 'Acme Corporation',
'domain' => 'acme.myapp.com',
'database' => 'tenant_acme',
'settings' => [
'max_users' => 100,
'features' => ['advanced_reporting', 'api_access'],
],
]);
// Setup tenant admin
$admin = TenantManager::createTenantAdmin($tenant, [
'name' => 'Admin User',
'email' => '[email protected] ',
'password' => 'SecurePassword123!',
]);
// Switch tenant context
TenantManager::switchToTenant($tenant);
// Check tenant limits
if (TenantManager::exceedsUserLimit($tenant)) {
throw new Exception('Tenant user limit exceeded');
}
// Get tenant statistics
$stats = TenantManager::getTenantStatistics($tenant);
// Configure password s' => [
'min_length' => 12,
'true,
'> true,
'prevent_keyboard_patterns' => true,
],
// Password history prevention
'password_history' => [
'enabled' => true,
'count' => 8, // Prevent reusing last 8 passwords
'check_similarity' => true,
],
// Password expiration
'password_expiration' => [
'enabled' => true,
'days' => 90,
'warn_days' => 14,
'force_change' => true,
],
// Configure account lockout
'account_lockout' => [
'enabled' => true,
'max_attempts' => 5,
'lockout_duration' => 15, // minutes
'progressive_delays' => true,
'notify_user' => true,
'track_by' => ['email', 'ip'], // Track attempts by email and IP
],
// Check if account is locked
if (Users::isAccountLocked($email)) {
$lockoutInfo = Users::getLockoutInfo($email);
// Show lockout message with remaining time
}
// Configure threat detection
'threat_detection' => [
'enabled' => true,
'unusual_location' => true,
'unusual_device' => true,
'unusual_time' => true,
'velocity_checks' => true,
'geo_blocking' => [
'enabled' => false,
'allowed_countries' => ['US', 'CA', 'GB'],
],
],
// Handle suspicious activity
Event::listen(SuspiciousActivityDetected::class, function ($event) {
// Send security alert
$event->user->notify(new SecurityAlertNotification($event));
// Require additional verification
Users::
// Register trusted device
$device = Users::registerDevice($user, [
'name' => 'iPhone 15 Pro',
'type' => 'mobile',
'fingerprint' => $deviceFingerprint,
'trusted' => false,
]);
// Trust device after verification
Users::trustDevice($user, $device);
// Check if device is trusted
if (Users::isDeviceTrusted($user, $deviceFingerprint)) {
// Skip 2FA for trusted device
}
// Get user devices
$devices = Users::getUserDevices($user);
// Revoke device
Users::revokeDevice($user, $deviceId);
// Configure session security
'session_security' => [
'secure_cookies' => true,
'http_only' => true,
'same_site' => 'strict',
'session_regeneration' => true,
'concurrent_sessions' => 3,
'idle_timeout' => 30, // minutes
'absolute_timeout' => 480, // minutes (8 hours)
],
// Monitor session activity
Users::trackSessionActivity($user, [
'action' => 'page_view',
'url' => request()->url(),
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
class UserRegistrationWorkflow extends Workflow
{
protected $steps = [
'validate_input', // Validate registration data
'check_email_availability', // Ensure email is unique
'create_user_account', // Create user record
'send_verification_email', // Send email verification
'wait_for_verification', // Wait for user to verify email
'assign_default_role', // Assign default role and permissions
'send_welcome_email', // Send welcome email
'trigger_onboarding', // Start onboarding process
];
public function validateInput($data)
{
$validator = validator($data, [
'name' => 'n $this->advance(['user' => $user]);
}
public function sendVerificationEmail($data)
{
$data['user']->sendEmailVerificationNotification();
return $this->advance();
}
// Workflow automatically waits for email verification
// When verified, workflow continues automatically
public function assignDefaultRole($data)
{
$defaultRole = config("users.user_types.{$data['user']->user_type}.default_role");
$data['user']->assignRole($defaultRole);
return $this->advance();
}
protected function onWorkflowCompleted($data)
{
event(new UserRegistrationCompleted($data['user']));
}
}
class ClientApprovalWorkflow extends Workflow
{
protected $steps = [
'validate_business_info',
'verify_business_documents',
'credit_check',
'admin_review',
'approval_decision',
'setup_client_account',
'send_approval_notification',
];
public function validateBusinessInfo($data)
{
// Validate business information
$rules = [
'business_name' => ' document verification service
$verificationResult = DocumentVerificationService::verify([
'business_license' => $data['business_license'],
'tax_id' => $data['tax_id'],
'business_name' => $data['business_name'],
]);
if (!$verificationResult['valid']) {
return $this->fail('Document verification failed: ' . $verificationResult['reason']);
}
return $this->advance([
'verification_id' => $verificationResult['id'],
'verified_at' => now(),
]);
}
public function adminReview($data)
{
// Create admin task for manual review
$task = AdminTask::create([
'type' => 'client_approval',
'title' => "Review client application: {$data['user']->name}",
'data' => $data,
'assigned_to' => $this->getNextAvailableAdmin(),
'due_date' => now()->addBusinessDays(2),
]);
// Send notification to admin
$task->assignedTo->notify(new ClientApprovalRequired($task));
// Wait for admin decision
return $this->pause([
'task_id' => $task->id,
'message' => 'Waiting for admin approval',
]);
}
public function setupClientAccount($data)
{
if ($data['approval_decision'] !== 'approved') {
return $this->fail('Application was not approved');
}
// Setup client-specific features
$data['user']->update(['status' => 'active']);
$data['user']->assignRole('client');
// Create client profile
$data['user']->profile()->create([
'company' => $data['business_name'],
'business_license' => $data['business_license'],
'tax_id' => $data['tax_id'],
]);
// Setup payment methods, API access, etc.
$this->setupClientServices($data['user']);
return $this->advance();
}
}
use Litepie\Flow\Workflow;
class CustomOnboardingWorkflow extends Workflow
{
protected $steps = [
'personal_info_collection',
'document_upload',
'background_check',
'training_assignment',
'equipment_provisioning',
'access_setup',
'welcome_orientation',
];
// Define timeout for each step
protected $stepTimeouts = [
'document_upload' => 48, // hours
'background_check' => 120, // hours (5 days)
'training_assignment' => 24, // hours
];
// Define notification rules
protected $notifications = [
'document_upload' => [
'reminder_after' => 24, // hours
'escalate_after' => 48, // hours
],
];
public function personalInfoCollection($data)
{
// Send form to user for additional information
$form = OnboardingForm::create([
'user_id' => $data['user']->id,
'type' => 'personal_info',
'fields' => $this->getPersonalInfoFields(),
'expires_at' => now()->addHours(72),
]);
// Send notification with form link
$data['user']->notify(new OnboardingFormRequired($form));
return $this->pause([
'form_id' => $form->id,
'message' => 'Waiting for personal information form completion',
]);
}
public function backgroundCheck($data)
{
// Initiate background check with third-party service
$checkId = BackgroundCheckService::initiate([
'user_id' => $data['user']->id,
'first_name' => $data['personal_info']['first_name'],
'last_name' => $data['personal_info']['last_name'],
'ssn' => $data['personal_info']['ssn'],
'date_of_birth' => $data['personal_info']['date_of_birth'],
]);
// Set up webhook to receive results
return $this->pause([
'background_check_id' => $checkId,
'message' => 'Background check in progress',
]);
}
protected function onStepTimeout($step, $data)
{
// Handle timeouts
switch ($step) {
case 'document_upload':
// Send reminder
$data['user']->notify(new DocumentUploadReminder());
break;
case 'background_check':
// Escalate to admin
$this->escalateToAdmin($data, 'Background check timeout');
break;
}
}
protected function onWorkflowFailed($reason, $data)
{
// Handle workflow failure
Log::error("Onboarding workflow failed for user {$data['user']->id}: {$reason}");
// Notify admin
Admin::notify(new OnboardingWorkflowFailed($data['user'], $reason));
// Update user status
$data['user']->update(['status' => 'onboarding_failed']);
}
}
// Get real-time user metrics
$metrics = Users::getRealTimeMetrics();
/*
Returns:
[
'online_users' => 145,
'active_sessions' => 289,
'registrations_today' => 23,
'logins_last_hour' => 67,
'failed_logins_last_hour' => 12,
'suspended_accounts' => 5,
'trending_user_types' => [
'client' => ['count' => 15, 'change' => '+23%'],
'regular' => ['count' => 8, 'change' => '-5%'],
],
]
*/
// Get user activity timeline
$timeline = Users::getActivityTimeline([
'period' => '24hours',
'granularity' => 'hour',
'events' => ['login', 'logout', 'registration', 'profile_update'],
]);
// Get geographic distribution
$geoData = Users::getGeographicDistribution([
'level' => 'country', // country, state, city
'limit' => 20,
'
// Security threat analysis
$threatAnalysis = Users::getSecurityThreatAnalysis([
'period' => '7days',
' 'detect_anomalies' => true,
'baseline_days' => 30,
]);
// Failed login attempts analysis
$failedLogins = Users::getFailedLoginAnalysis([
'period' => '24hours',
'group_by' => 'ip_address',
'min_attempts' => 3,
]);
use Litepie\Users\Reports\ReportBuilder;
$report = ReportBuilder::create('user_acquisition')
->title('Monthly User Acquisition Report')
->description('Detailed analysis of user registrations and conversions')
->dateRange(now()->startOfMonth(), now()->endOfMonth())
->filters([
'user_types' => ['regular', 'client'],
'status' => ['active', 'pending'],
'exclude_test_users' => true,
])
->metrics([
'total_registrations',
'conversion_rate',
'average_time_to_activation',
'retention_rate_7_days',
'retention_rate_30_days',
])
->groupBy('day')
->visualization('line_chart')
->generate();
// Export report
$export = $report->export([
'format' => 'pdf',
'
// Cohort analysis
$cohortAnalysis = Users::getCohortAnalysis([
'cohort_by' => 'registration_month',
'measure' => 'retention',
'periods' => 12, // 12 months
' 'first_login',
'feature_usage',
],
'period' => '30days',
'segment_by' => 'user_type',
]);
// A/B test analysis
$abTestResults = Users::getABTestResults([
'test_name' => 'registration_flow_v2',
'variants' => ['control', 'variation_a', 'variation_b'],
'success_metric' => 'completed_registration',
'period' => '14days',
]);
// Monitor system performance
$performance = Users::getPerformanceMetrics([
'/ Database query analysis
$queryAnalysis = Users::getDatabaseQueryAnalysis([
'slow_query_threshold' => 1000, // milliseconds
'period' => '1hour',
'
use Litepie\Users\Testing\UserTestHelper;
use Litepie\Users\Models\User;
class UserManagementTest extends TestCase
{
use UserTestHelper;
/** @test */
public function it_can_create_user_with_profile()
{
$user = $this->createUserWithProfile([
'user_type' => 'client',
'profile' => [
'company' => 'Test Company',
'phone' => '+1-555-123-4567',
],
]);
$this->assertDatabaseHas('users', ['id' => $user->id]);
$this->assertDatabaseHas('user_profiles', [
'user_id' => $user->id,
'company' => 'Test Company',
]);
}
/** @test */
public function it_enforces_password_complexity()
{
$this->expectException(ValidationException::class);
$this->createUser(['password' => 'weak']);
}
/** @test */
public function it_can_assign_roles_and_permissions()
{
$user = $this->createUser();
$role = $this->createRole('manager');
$permission = $this->createPermission('edit_posts');
$user->assignRole($role);
$user->givePermissionTo($permission);
$this->assertTrue($user->hasRole('manager'));
$this->assertTrue($user->can('edit_posts'));
}
/** @test */
public function it_handles_tenant_isolation()
{
$tenant1 = $this->createTenant();
$tenant2 = $this->createTenant();
$user1 = $this->createUserForTenant($tenant1);
$user2 = $this->createUserForTenant($tenant2);
$this->actingAsTenant($tenant1);
$this->assertCount(1, User::all());
$this->actingAsTenant($tenant2);
$this->assertCount(1, User::all());
}
}
class UserApiTest extends TestCase
{
use RefreshDatabase, WithFaker;
/** @test */
public function it_can_register_new_user_via_api()
{
$userData = [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => 'SecurePassword123!',
'password_confirmation' => 'SecurePassword123!',
'user_type' => 'regular',
];
$response = $this->postJson('/api/auth/register', $userData);
$response->assertStatus(201)
->assertJsonStructure([
'success',
'data' => [
'id',
'name',
'email',
'user_type',
'status',
],
'meta' => ['token'],
]);
$this->assertDatabaseHas('users', [
'email' => $userData['email'],
'user_type' => 'regular',
'status' => 'pending',
]);
}
/** @test */
public function it_
class UserSecurityTest extends TestCase
{
/** @test */
public function it_prevents_sql_injection_in_user_search()
{
$maliciousInput = "'; DROP TABLE users; --";
$response = $this->getJson("/api/users?search={$maliciousInput}");
$response->assertStatus(200);
$this->assertDatabaseHas('users', ['id' => 1]); // Table still exists
}
/** @test */
public function it_prevents_mass_assignment_vulnerabilities()
{
$user = User::factory()->create(['user_type' => 'regular']);
$response = $this->actingAs($user)
->putJson("/api/profile", [
'name' => 'Updated Name',
'user_type' => 'admin', // Trying to escalate privileges
'status' => 'active',
]);
$response->assertStatus(200);
$user->refresh();
$this->assertEquals('regular', $user->user_type); // Type unchanged
$this->assertEquals('Updated Name', $user->name); // Name updated
}
/** @test */
public function it_enforces_rate_limiting()
{
for ($i = 0; $i < 6; $i++) {
$response = $this->postJson('/api/auth/login', [
'email' => '[email protected] ',
'password' => 'wrong-password',
]);
}
$response->assertStatus(429); // Too Many Requests
}
}
use Litepie\Users\UserTypes\BaseUserType;
class VendorUserType extends BaseUserType
{
/**
* Get the registration workflow for this user type
*/
public function getRegistrationWorkflow(): string
{
return VendorRegistrationWorkflow::class;
}
/**
* Get default permissions for this user type
*/
public function getDefaultPermissions(): array
{
return [
'vendor.manage_products',
'vendor.view_orders',
'vendor.manage_inventory',
'vendor.view_analytics',
];
}
/**
* Get validation rules specific to this user type
*/
public function getValidationRules(): array
{
return array_merge(parent::getValidationRules(), [
'business_license' => '
// Send vendor welcome package
$user->notify(new VendorWelcomeNotification());
}
/**
* Get dashboard configuration
*/
public function getDashboardConfig(): array
{
return [
'layout' => 'vendor',
'widgets' => [
'sales_overview',
'product_performance',
'order_management',
'inventory_alerts',
],
'menu_items' => [
'Products' => 'vendor.products.index',
'Orders' => 'vendor.orders.index',
'Analytics' => 'vendor.analytics.index',
'Settings' => 'vendor.settings.index',
],
];
}
/**
* Get notification preferences
*/
public function getNotificationPreferences(): array
{
return [
'order_notifications' => true,
'payment_alerts' => true,
'inventory_warnings' => true,
'performance_reports' => 'weekly',
];
}
/**
* Custom profile fields
*/
public function getProfileFields(): array
{
return [
'business_name' => '
// config/users.php
'user_types' => [
'vendor' => [
'class' => \App\UserTypes\VendorUserType::class,
'label' => 'Vendor',
'description' => 'Business vendor with product management capabilities',
'registration_enabled' => true,
'auto_activate' => false,
'default_role' => 'vendor',
'workflow' => 'vendor_registration',
],
],
use Litepie\Users\Contracts\UserProfileExtension;
class CustomProfileExtension implements UserProfileExtension
{
/**
* Get additional fillable fields
*/
public function getFillableFields(): array
{
return [
'employee_id',
'department',
'manager_id',
'hire_date',
'salary_grade',
'security_clearance',
'emergency_contact',
];
}
/**
* Get validation rules for custom fields
*/
public function getValidationRules(): array
{
return [
'employee_id' => 'nullable|string|unique:user_profiles',
'department' => 'nullable|string|max:100',
'manager_id' => 'nullable|exists:users,id',
'hire_date' => 'nullable|date',
'salary_grade' => 'nullable|in:1,2,3,4,5',
'security_clearance' => 'nullable|in:public,confidential,secret,top_secret',
'emergency_contact' => 'nullable|json',
];
}
/**
* Get field labels for forms
*/
public function getFieldLabels(): array
{
return [
'employee_id' => 'Employee ID',
'department' => 'Department',
'manager_id' => 'Manager',
'hire_date' => 'Hire Date',
'salary_grade' => 'Salary Grade',
'security_clearance' => 'Security Clearance',
'emergency_contact' => 'Emergency Contact',
];
}
/**
* Get relationships
*/
public function getRelationships(): array
{
return [
'manager' => 'belongsTo:App\Models\User',
'subordinates' => 'hasMany:App\Models\User,manager_id',
];
}
/**
* Process field data before saving
*/
public function processFieldData(array $data): array
{
if (isset($data['emergency_contact']) && is_array($data['emergency_contact'])) {
$data['emergency_contact'] = json_encode($data['emergency_contact']);
}
return $data;
}
}
// In a service provider
Users::extendProfile(CustomProfileExtension::class);
// Listen to user events
Event::listen('users.user.creating', function ($user) {
// Pre-creation validation or modification
if ($user->user_type === 'premium') {
$user->stripe_customer_id = StripeService::createCustomer($user);
}
});
Event::listen('users.user.created', function ($user) {
// Post-creation actions
WelcomeEmailJob::dispatch($user);
AnalyticsService::track('user_registered', $user);
});
Event::listen('users.user.activating', function ($user) {
// Before activation
if (!LicenseService::hasAvailableSeats()) {
throw new Exception('No available licenses');
}
});
Event::listen('users.user.activated', function ($user) {
// After activation
LicenseService::assignSeat($user);
OnboardingWorkflow::start($user);
});
Event::listen('users.user.login', function ($user, $request) {
// Track login activity
LoginAnalytics::record($user, $request);
// Check for suspicious activity
if (SecurityService::isSuspiciousLogin($user, $request)) {
SecurityAlert::dispatch($user, $request);
}
});
Event::listen('users.user.password_changed', function ($user) {
// Password change actions
SecurityLog::create([
'user_id' => $user->id,
'event' => 'password_changed',
'ip_address' => request()->ip(),
]);
// Invalidate all sessions except current
SessionService::invalidateOtherSessions($user);
});
Event::listen('users.profile.updated', function ($user, $changes) {
// Track profile changes
foreach ($changes as $field => $value) {
AuditLog::create([
'user_id' => $user->id,
'action' => 'profile_updated',
'field' => $field,
'old_value' => $user->getOriginal($field),
'new_value' => $value,
]);
}
});
class EnhancedUserMiddleware
{
public function handle($request, Closure $next, ...$guards)
{
$user = auth()->user();
if ($user) {
// Update last activity
$user->update(['last_activity_at' => now()]);
// Check if user needs to change password
if ($this->passwordExpired($user)) {
return redirect()->route('password.change')
->with('warning', 'Your password has expired.');
}
// Check security }
$expiryDays = config('users.password_expiration.days', 90);
return $user->password_changed_at->diffInDays(now()) >= $expiryDays;
}
private function y' => $location->country,
'city' => $location->city,
'coordinates' => $location->coordinates,
'accessed_at' => now(),
]);
}
}
// Configure caching
'cache' => [
'enabled' => true,
'default_ttl' => 3600, // 1 hour
'stores' => [
'users' => 'redis',
'permissions' => 'redis',
'sessions' => 'redis',
],
'tags' => [
'users' => 'users',
'profiles' => 'user_profiles',
'roles' => 'user_roles',
'permissions' => 'user_permissions',
],
'strategies' => [
'user_data' => 'write_through',
'permissions' => 'write_behind',
'analytics' => 'lazy_loading',
],
],
// Cache warming
'cache_warming' => [
'enabled' => true,
'schedule' => '0 2 * * *', // Daily at 2 AM
'warm_data' => [
'active_users',
'user_permissions',
'role_hierarchies',
'user_preferences',
],
],
// Automatic caching with model
$user = Cache::remember("user.{$id}", 3600, function () use ($id) {
return User::with(['profile', 'roles'])->find($id);
});
// Cache user permissions
$permissions = Cache::tags(['user_permissions'])
->remember("user.{$userId}.permissions", 7200, function () use ($userId) {
return User::find($userId)->getAllPermissions();
});
// Invalidate user cache on updates
Event::listen('users.user.updated', function ($user) {
Cache::tags(['users'])->flush();
Cache::forget("user.{$user->id}");
Cache::forget("user.{$user->id}.permissions");
});
// Batch cache operations
$userIds = [1, 2, 3, 4, 5];
$users = Cache::many(
collect($userIds)->mapWithKeys(fn($id) => ["user.{$id}" => null])->all()
);
// Fill missing cache entries
$missingIds = collect($userIds)->reject(fn($id) => isset($users["user.{$id}"]));
if ($missingIds->isNotEmpty()) {
$freshUsers = User::whereIn('id', $missingIds)->get()->keyBy('id');
foreach ($freshUsers as $user) {
Cache::put("user.{$user->id}", $user, 3600);
$users["user.{$user->id}"] = $user;
}
}
// Optimized user queries with eager loading
$users = User::with([
'profile:id,user_id,first_name,last_name,avatar',
'roles:id,name',
'tenant:id,name'
])
->select(['id', 'name', 'email', 'user_type', 'status', 'tenant_id'])
->where('status', 'active')
->orderBy('created_at', 'desc')
->paginate(25);
// Chunked processing for large datasets
User::where('status', 'inactive')
->whereDate('last_login_at', '<', now()->subMonths(6))
->chunk(1000, function ($users) {
foreach ($users as $user) {
$user->archive();
}
});
// Efficient search with full-text search
$searchResults = User::search($query)
->with(['profile', 'roles'])
->paginate(20);
// Optimized permission checking
$user->loadMissing(['roles.permissions', 'permissions']);
$hasPermission = $user->can($permission); // Uses loaded relations
// Database configuration for high-performance
'database' => [
'connections' => [
'mysql' => [
'read' => [
'host' => [
'read-replica-1.mysql.example.com',
'read-replica-2.mysql.example.com',
],
],
'write' => [
'host' => 'primary.mysql.example.com',
],
'options' => [
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode='STRICT_TRANS_TABLES'",
],
'pool' => [
'min_connections' => 5,
'max_connections' => 20,
'connection_timeout' => 30,
],
],
],
],
// Queue configuration
'queue' => [
'default' => 'redis',
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'users',
'retry_after' => 90,
'block_for' => null,
],
],
'failed' => [
'driver' => 'database',
'database' => 'mysql',
'table' => 'failed_jobs',
],
'batching' => [
'driver' => 'database',
'table' => 'job_batches',
],
],
// Batch job processing
Bus::batch([
new SendWelcomeEmail($user1),
new SendWelcomeEmail($user2),
new SendWelcomeEmail($user3),
])->then(function (Batch $batch) {
// All emails sent successfully
})->catch(function (Batch $batch, Throwable $e) {
// Handle batch failure
})->finally(function (Batch $batch) {
// Cleanup
})->dispatch();
// Priority queues
dispatch(new UrgentSecurityAlert($user))->onQueue('high-priority');
dispatch(new SendNewsletterJob($users))->onQueue('low-priority');
// Issue: Token validation fails
// Clear auth cache
php artisan auth:clear-resets
php artisan cache:clear
// Issue: Session not persisting
// Check session configuration
'session' => [
'driver' => 'database', // or 'redis'
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => true,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'store' => null,
'lottery' => [2, 100],
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
'secure' => null,
'http_only' => true,
'same_site' => 'lax',
];
// Issue: Permissions not working
// Clear permission cache
php artisan permission:cache-reset
// Issue: Role assignments not persisting
// Check model trait usage
class User extends Authenticatable
{
use HasRoles, HasPermissions; // Make sure traits are
// Issue: Slow user queries
// Enable query logging
DB::enableQueryLog();
$users = User::with('profile', 'roles')->get();
dd(DB::getQueryLog());
// Issue: Memory exhaustion on large datasets
// Use chunking for large operations
User::chunk(1000, function ($users) {
foreach ($users as $user) {
// Process user
}
});
// Issue: Cache not working
// Verify cache configuration
php artisan config:cache
php artisan cache:clear
redis-cli ping # For Redis cache
// config/users.php
'debug' => [
'enabled' => env('USERS_DEBUG', false),
'log_queries' => env('USERS_LOG_QUERIES', false),
'log_permissions' => env('USERS_LOG_PERMISSIONS', false),
'log_workflows' => env('USERS_LOG_WORKFLOWS', false),
'performance_monitoring' => env('USERS_PERFORMANCE_MONITORING', false),
],
// Enable debug logging
Log::channel('users')->info('User operation', [
'user_id' => $user->id,
'action' => 'login',
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
// Performance monitoring
$start = microtime(true);
$users = User::complex_query()->get();
$duration = microtime(true) - $start;
if ($duration > 1.0) { // Log slow queries
Log::warning('Slow query detected', [
'duration' => $duration,
'query' => 'User::complex_query',
]);
}
// Health check endpoint
Route::get('/health/users', function () {
$checks = [
'database' => Users::checkDatabaseConnection(),
'cache' => Users::checkCacheConnection(),
'queue' => Users::checkQueueConnection(),
'storage' => Users::checkStorageAccess(),
'permissions' => Users::checkPermissionSystem(),
];
$healthy = collect($checks)->every(fn($check) => $check['status'] === 'ok');
return response()->json([
'status' => $healthy ? 'healthy' : 'unhealthy',
'checks' => $checks,
'timestamp' => now(),
], $healthy ? 200 : 503);
});
// Automated health monitoring
php artisan users:health-check [email protected]
// OLD (v1.x)
$user->addRole('admin');
$user->hasPermission('edit_posts');
// NEW (v2.x)
$user->assignRole('admin');
$user->can('edit_posts');
// OLD (v1.x)
Users::createUser($data);
// NEW (v2.x)
User::create($data); // or Users::create($data)
// OLD (v1.x)
'user_types' => ['admin', 'user']
// NEW (v2.x)
'user_types' => [
'admin' => ['class' => AdminUserType::class],
'user' => ['class' => RegularUserType::class],
]
// Migrate existing single-tenant to multi-tenant
php artisan users:migrate-to-tenancy
// This will:
// 1. Add tenant_id columns to all user tables
// 2. Create default tenant for existing data
// 3. Update foreign key constraints
// 4. Add tenant scoping to models
return [
// User types configuration
'user_types' => [
'regular' => RegularUserType::class,
'client' => ClientUserType::class,
'admin' => AdminUserType::class,
'system' => SystemUserType::class,
],
// Registration settings (Laravel 12 enhanced)
'registration' => [
'enabled' => true,
'auto_activate' => false,
'auto_login' => false,
'allowed_types' => ['regular', 'client'],
'captcha_enabled' => env('USERS_CAPTCHA_ENABLED', false),
'email_verification' => true,
'rate_limit' => 5, // Laravel 12 enhanced rate limiting
'honeypot_enabled' => true, // Laravel 12 security feature
],
// Authentication settings (Laravel 12 optimized)
'authentication' => [
'login_attempts_limit' => 5,
'lockout_duration' => 15, // minutes
'password_min_length' => 12, // Increased for Laravel 12 security
'password_history_count' => 8, // Enhanced security
'session_timeout' => 120, // minutes
'two_factor_
use Litepie\Users\Facades\Users;
// Create a regular user (Laravel 12 enhanced)
$user = Users::createUser([
'name' => 'John Doe',
'email' => '[email protected] ',
'password' => 'SecureP@ssw0rd123', // Laravel 12 mail' => '[email protected] ',
'password' => 'SecureP@ssw0rd123',
'user_type' => 'client',
'profile' => [
'company' => 'Acme Corporation',
'website' => 'https://acme.com',
'business_license' => 'BL123456789', // Laravel 12 enhanced validation
],
'metadata' => [ // Laravel 12 feature
'source' => 'web_registration',
'utm_campaign' => 'summer_2025',
],
]);
// Activate a user with Laravel 12 enhanced logging
Users::activateUser($user, [
'reason' => 'Email verified',
'activated_by' => auth()->id(),
'activation_method' => 'email_verification',
]);
// Suspend a user with detailed tracking
Users::suspendUser($user, [
'reason' => 'Policy violation',
'suspended_by' => auth()->id(),
'suspension_duration' => now()->addDays(7),
]);
// Assign role with Laravel 12 enhanced permissions
Users::assignRole($user, 'manager', [
'assigned_by' => auth()->id(),
'scope' => 'tenant', // Laravel 12 scoped permissions
'expires_at' => now()->addMonths(6),
]);
// Update user profile with Laravel 12 validation
Users::updateProfile($user, [
'first_name' => 'John',
'last_name' => 'Doe',
'bio' => 'Software developer',
'preferences' => [ // Laravel 12 feature
'theme' => 'dark',
'notifications' => ['email', 'push'],
'language' => 'en',
],
]);
// Laravel 12 specific features
Users::enableSecurityFeatures($user, [
'two_factor_auth' => true,
'device_verification' => true,
'login_notifications' => true,
]);
use Litepie\Users\UserTypes\RegularUserType;
use Litepie\Users\UserTypes\ClientUserType;
// Get user type instance
$userType = new RegularUserType();
// Check registration workflow
$workflow = $userType->getRegistrationWorkflow();
// Get default permissions
$permissions = $userType->getDefaultPermissions();
// Validate user data
$isValid = $userType->validateUserData($userData);
// Users are automatically scoped to current tenant with Laravel 12 optimizations
$users = User::all(); // Only returns users for current tenant with enhanced caching
// Create tenant-specific user with Laravel 12 features
tenant()->users()->create([
'name' => 'Tenant User',
'email' => '[email protected] ',
'password' => bcrypt('SecureP@ssw0rd123'),
'tenant_scoped_permissions' => ['manage_content', 'view_analytics'],
]);
// Laravel 12 enhanced tenant isolation
$tenantUsers = User::withTenantScope()
->where('status', 'active')
->with(['profile', 'roles'])
->cache(300) // Laravel 12 enhanced caching
->get();
// Cross-tenant operations (admin only) with Laravel 12 security
if (auth()->user()->hasRole('super_admin')) {
$allUsers = User::withoutTenantScope()
->secureQuery() // Laravel 12 security feature
->get();
}
use Litepie\Users\Workflows\UserRegistrationWorkflow;
// Start registration workflow
$workflow = new UserRegistrationWorkflow();
$workflow->start([
'name' => 'John Doe',
'email' => '[email protected] ',
'user_type' => 'client',
]);
// The workflow will handle:
// - Email verification
// - Admin approval (if
// Upload avatar
$file = $user->uploadAvatar($request->file('avatar'));
// Get avatar URL
$avatarUrl = $user->avatar_url;
// Attach files to user
$user->attachFile($file, [
'title' => 'Profile Document',
'category' => 'identity',
]);
// Get user statistics
$stats = Users::getUserStatistics();
// Get registration statistics
$registrationStats = Users::getRegistrationStatistics('30days');
// Get activity statistics
$activityStats = Users::getActivityStatistics('7days');
// Get user type distribution
$typeStats = Users::getUserTypeStatistics();
// Configure in config/users.php
'authentication' => [
'login_attempts_limit' => 5,
'lockout_duration' => 15, // minutes
],
// Laravel 12 enhanced password security
'authentication' => [
'password_history_count' => 8, // Prevent reuse of last 8 passwords
'password_min_length' => 12, // Increased minimum length
'password_complexity' => [
'
],
// Enable 2FA for a user with Laravel 12 features
$twoFactorData = Users::enableTwoFactorAuth($user, [
'method' => 'totp', // totp, sms, email
'backup_codes' => true,
'device_trust' => true, // Laravel 12 feature
]);
// Disable 2FA with secure verification
Users::disableTwoFactorAuth($user, [
'verification_method' => 'password',
'verification_value' => $password,
]);
// Verify 2FA token with Laravel 12 enhancements
$isValid = Users::verifyTwoFactorToken($user, $token, [
'method' => 'totp',
'trust_device' => true,
'device_id' => request()->header('X-Device-ID'),
]);
// Laravel 12 specific 2FA features
Users::configureTwoFactorSettings($user, [
'
// Core user events
Litepie\Users\Events\UserRegistered::class
Litepie\Users\Events\UserActivated::class
Litepie\Users\Events\UserRoleChanged::class
Litepie\Users\Events\UserLoggedIn::class
Litepie\Users\Events\UserProfileUpdated::class
// Laravel 12 enhanced security events
Litepie\Users\Events\SuspiciousLoginDetected::class
Litepie\Users\Events\DeviceVerificationRequired::class
Litepie\Users\Events\PasswordExpired::class
Litepie\Users\Events\TwoFactorEnabled::class
Litepie\Users\Events\TwoFactorDisabled::class
// Multi-tenancy events
Litepie\Users\Events\UserTenantChanged::class
Litepie\Users\Events\TenantUserLimitReached::class
// Workflow events
Litepie\Users\Events\WorkflowCompleted::class
Litepie\Users\Events\ApprovalRequired::class
// In EventServiceProvider (Laravel 12 auto-discovery supported)
protected $listen = [
\Litepie\Users\Events\UserRegistered::class => [
\App\Listeners\SendWelcomeEmail::class,
\App\Listeners\CreateUserDirectory::class,
\App\Listeners\InitializeUserPreferences::class, // Laravel 12 feature
],
\Litepie\Users\Events\SuspiciousLoginDetected::class => [
\App\Listeners\NotifySecurityTeam::class,
\App\Listeners\RequireAdditionalVerification::class,
],
];
// Laravel 12 closure-based listeners
Event::listen(
\Litepie\Users\Events\UserLoggedIn::class,
function ($event) {
// Update last activity with Laravel 12 performance optimizations
Cache::tags(['user:' . $event->user->id])
->put('last_activity', now(), 3600);
}
);
use Litepie\Users\UserTypes\BaseUserType;
class VendorUserType extends BaseUserType
{
public function getRegistrationWorkflow(): string
{
return VendorRegistrationWorkflow::class;
}
public function getDefaultPermissions(): array
{
return ['vendor.manage_products', 'vendor.view_orders'];
}
public function getValidationRules(): array
{
return array_merge(parent::getValidationRules(), [
'business_license' => ' 'password_complexity' => 'high',
];
}
public function getDefaultPreferences(): array
{
return [
'dashboard_layout' => 'vendor',
'notifications' => [
'order_notifications' => true,
'payment_alerts' => true,
'product_updates' => false,
],
'api_access' => true,
];
}
}
// In config/users.php
'user_types' => [
'vendor' => VendorUserType::class,
],
use Litepie\Flow\Workflow;
class VendorRegistrationWorkflow extends Workflow
{
protected $steps = [
'validate_business_info',
'verify_business_license',
'check_credit_score', // Laravel 12 integration
'admin_approval',
'setup_vendor_account',
'configure_payment_methods', // Laravel 12 feature
'setup_api_access',
'send_welcome_package',
];
public function validateBusinessInfo($data)
{
// Laravel 12 enhanced validation with async processing
return $this->validateAsync([
'business_license' => 'BusinessCreditJob($data));
}
protected function onWorkflowCompleted($data)
{
// Laravel 12 event broadcasting
broadcast(new VendorApprovalCompleted($data['user']));
// Setup Laravel 12 specific features
$this->setupVendorDashboard($data['user']);
$this->createApiCredentials($data['user']);
}
}
bash
php artisan users:install
bash
php artisan users:create-admin
bash
curl -X POST /api/bulk/users/assign-role \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"user_ids": [1, 2, 3, 4, 5],
"role": "manager",
"expires_at": "2025-12-31T23:59:59Z",
"notify_users": true
}'
bash
# Issue: Migration fails due to existing tables
php artisan migrate:status
php artisan migrate:rollback --step=1
php artisan migrate
# Issue: Foreign key constraints
php artisan migrate:fresh --seed
# Issue: Permission denied on database
# Check database permissions and user privileges
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
FLUSH PRIVILEGES;