PHP code example of mcbanks / mcbankslaravel

1. Go to this page and download the library: Download mcbanks/mcbankslaravel 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/ */

    

mcbanks / mcbankslaravel example snippets


// Get all countries
$countries = Country::all();

// Get states for a specific country
$states = State::where('country_id', 1)->get();

// Get cities in a state
$cities = City::where('state_id', 1)->get();

// Get Kenyan counties
$counties = County::all();

// Get constituencies in a county
$constituencies = SubCounty::getUniqueConstituencies(1);

// Get wards in a constituency
$wards = SubCounty::getWardsByConstituency(1, 'changamwe');

// Get all wards in Kenya (filtered, no duplicates)
$allWards = SubCounty::getAllUniqueWards();

$user = User::find(1);
$user->assignRole('admin'); // Assign admin role

if ($user->hasRole('new_role')) {
    return '/new-dashboard';
}

use App\Services\TwoFactorService;

$user = Auth::user();
$twoFactorService = app(TwoFactorService::class);

// Generate secret key and QR code
$secret = $twoFactorService->generateSecretKey($user);
$qrCode = $twoFactorService->generateQrCode($user, $secret);

// Enable 2FA after user verification
$twoFactorService->enable($user, $verificationCode);

// Check if user has 2FA enabled
if ($user->hasTwoFactorEnabled()) {
    // Verify user code
    if ($user->verifyTwoFactorCode($request->code)) {
        // Authentication successful
        $user->twoFactorAuthentication->updateLastUsed();
    }
}

$user->disableTwoFactor();

// Two-Factor Authentication
Route::middleware(['auth', 'throttle:5,1'])->group(function () {
    Route::get('/2fa/challenge', [TwoFactorController::class, 'showChallenge'])->name('2fa.challenge');
    Route::post('/2fa/verify', [TwoFactorController::class, 'verify'])->name('2fa.verify');
    Route::get('/2fa/recovery', [TwoFactorController::class, 'showRecoveryForm'])->name('2fa.recovery');
    Route::post('/2fa/recovery/verify', [TwoFactorController::class, 'verifyRecovery'])->name('2fa.recovery.verify');
    Route::post('/2fa/logout', [TwoFactorController::class, 'logout'])->name('2fa.logout');
});

// app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        // ... existing middleware
        \App\Http\Middleware\LogUserActivity::class,
    ],
    'api' => [
        // ... existing middleware
        \App\Http\Middleware\RateLimitApi::class,
    ],
];

protected $middlewareAliases = [
    'rate.limit.auth' => \App\Http\Middleware\RateLimitAuth::class,
    'rate.limit.profile' => \App\Http\Middleware\RateLimitProfile::class,
];

use App\Services\RateLimitingService;

$rateLimiting = app(RateLimitingService::class);

// Check authentication rate limit
if ($rateLimiting->checkAuthRateLimit($request)) {
    abort(429, 'Too many attempts');
}

// Check API rate limit
if ($rateLimiting->checkApiRateLimit($request)) {
    abort(429, 'API rate limit exceeded');
}

// Get rate limit information for current user
$status = $rateLimiting->getRateLimitStatus($request, 'auth', 5);

// Output rate limit headers
$headers = $rateLimiting->getRateLimitHeaders($request, 'api', 1000, 60);
foreach ($headers as $key => $value) {
    $response->headers->set($key, $value);
}

// Blacklist an IP address
$rateLimiting->blacklistIp('192.168.1.100', 60); // 60 minutes

// Check if IP is blacklisted
if ($rateLimiting->isIpBlacklisted($request->ip())) {
    abort(429, 'Your IP has been blocked');
}

// Remove IP from blacklist
$rateLimiting->unblacklistIp('192.168.1.100');

// Log suspicious activity for monitoring
$rateLimiting->logSuspiciousActivity($request, 'multiple_failed_logins');

// Check for suspicious activity patterns
if ($rateLimiting->checkSuspiciousActivityRateLimit($request)) {
    // Take action against suspicious user
}

// Login attempts
RateLimitAuth: 5 attempts per 15 minutes

// Registration attempts  
RateLimitAuth: 3 attempts per hour

// Password reset requests
RateLimitAuth: 3 attempts per hour

// Authenticated users
RateLimitApi: 1000 requests per hour

// Anonymous users
RateLimitApi: 100 requests per hour

// Specific endpoints
RateLimitApi: Custom limits per endpoint

// Profile updates
RateLimitProfile: 10 attempts per hour

// Avatar uploads
RateLimitProfile: 5 attempts per hour

// Profile views (more lenient)
RateLimitProfile: 200 attempts per hour

// app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        // ... existing middleware
        \App\Http\Middleware\LogUserActivity::class,
    ],
];

use App\Services\AuditService;
use App\Models\AuditLog;

$auditService = app(AuditService::class);

// Log authentication event
$auditService->logAuth('login', [
    'user_id' => $user->id,
    'ip_address' => $request->ip(),
    'user_agent' => $request->userAgent(),
]);

// Log profile change
$auditService->logProfileChange('profile_updated', $user, $oldValues, $newValues);

// Log security event
$auditService->logSecurity('suspicious_login', 'Multiple failed logins detected', [
    'ip_address' => $request->ip(),
    'attempts' => 5,
], 'warning');

// Get user's audit logs
$logs = $auditService->getUserLogs($user, 50, [
    'start_date' => now()->subDays(30),
    'end_date' => now(),
    'level' => 'warning'
]);

// Get security events
$securityLogs = $auditService->getSecurityLogs(100);

// Get error logs
$errorLogs = $auditService->getErrorLogs(50);

// Using the AuditLog model directly
AuditLog::log([
    'user_id' => auth()->id(),
    'action' => 'profile_updated',
    'description' => 'User updated their profile',
    'old_values' => ['name' => 'Old Name'],
    'new_values' => ['name' => 'New Name'],
    'model_type' => \App\Models\Profile::class,
    'model_id' => $profile->id,
    'level' => 'info',
]);

// Successful login
AuditLog::logLogin($user, $ipAddress, $userAgent);

// Failed login attempt
AuditLog::logLoginFailed($email, $ipAddress, $userAgent);

// User logout
AuditLog::logLogout($user, $ipAddress, $userAgent);

// 2FA enabled
AuditLog::logTwoFactorEnabled($user);

// 2FA disabled
AuditLog::logTwoFactorDisabled($user);

// 2FA verification failed
AuditLog::logTwoFactorFailed($user, $ipAddress);

// Recovery code used
AuditLog::logRecoveryCodeUsed($user, $ipAddress);

// Profile updated
AuditLog::logProfileUpdate($user, $oldValues, $newValues);

// Password reset requested
AuditLog::logPasswordResetRequest($user, $ipAddress);

// Password reset completed
AuditLog::logPasswordResetCompleted($user, $ipAddress);

// Social account connected
AuditLog::logSocialAccountConnected($user, 'google', $ipAddress);

// Social account disconnected
AuditLog::logSocialAccountDisconnected($user, 'github', $ipAddress);

// Get audit statistics
$stats = $auditService->getStatistics();

// Returns:
// - total_logs, last_24_hours, last_7_days, last_30_days
// - security_events, error_events, unique_users
// - top_actions, top_ips, activity_by_level

// Detect suspicious patterns
$patterns = $auditService->getSuspiciousActivity();

// Returns:
// - multiple_failed_logins (same IP, many attempts)
// - rapid_profile_updates (same user, many changes)
// - unusual_ip_activity (user from many IPs)

// Check for security anomalies
$anomalies = $auditService->checkSecurityAnomalies();

// Returns:
// - concurrent_logins (same user, different IPs)
// - excessive_password_resets (same IP, many requests)

// Export audit logs to CSV
$csv = $auditService->exportToCSV([
    'start_date' => now()->subDays(30),
    'end_date' => now(),
    'user_id' => $userId,
]);

// Cleanup old logs (automatic retention)
$deleted = $auditService->cleanupOldLogs(90); // Keep 90 days

// Get user profile
$user = Auth::user();
$profile = $user->profile ?? $user->getOrCreateProfile();

// Check profile completion
if ($user->hasCompleteProfile()) {
    // User has 80%+ complete profile
}

// Get avatar URL
$avatarUrl = $user->avatar_url;
$thumbnailUrl = $user->thumbnail_url;

// Calculate completion percentage
$percentage = $profile->calculateCompletionPercentage();

// Update completion percentage
$profile->updateCompletionPercentage();

// Get completion status message
$message = $profile->completion_percentage < 50 
    ? 'Profile needs more information' 
    : 'Looking good!';

// Check if user can view another profile
if (auth()->user()->canViewProfile($targetUser)) {
    // Show profile
}

// Get privacy settings
$privacy = $profile->privacy_settings;
$showPhone = $privacy['show_phone'] ?? true;

use App\Services\SocialAuthService;

// Handle social login
$socialUser = Socialite::driver('google')->user();
$user = $socialAuthService->handleSocialLogin('google', $socialUser);

// Check user social accounts
if ($user->hasSocialAccount('google')) {
    $googleAccount = $user->getSocialAccount('google');
}

// Disconnect social account
$socialAuthService->disconnectSocialAccount($user, 'google');

// Get connected providers
$providers = $user->connected_providers; // ['google', 'github']

// Check token validity
$socialAccount = $user->getSocialAccount('google');
if ($socialAccount->hasValidToken()) {
    // Token is valid
}

// Get provider-specific data
$avatar = $socialAccount->avatar_url;
$nickname = $socialAccount->nickname;

// Add new field
public $new_field = '';
// Add validation
protected $rules['new_field'] = ['

if ($user->hasRole('new_role')) {
    return '/new-route';
}
bash
php artisan migrate
bash
php artisan serve
blade
<livewire:auth.registration-form />
blade
<livewire:auth.login-form />
bash
# Create default roles
php artisan role:create admin
php artisan role:create host
php artisan role:create guest

# Create custom roles
php artisan role:create moderator
php artisan role:create editor
php artisan role:create subscriber
bash
# Create standard roles
php artisan role:create admin
php artisan role:create member
php artisan role:create customer
php artisan role:create manager

# Create custom roles
php artisan role:create moderator
php artisan role:create editor
php artisan role:create subscriber
bash
php artisan db:seed --class=ProfileSeeder
php artisan db:seed --class=SocialAccountSeeder
bash
php artisan migrate --force
bash
npm run build
php artisan config:cache
php artisan route:cache
php artisan view:cache
bash
php artisan queue:work
bash
# Install te

# Run migrations
php artisan migrate

# Add middleware to app/Http/Kernel.php
'2fa.challenge' => \App\Http\Middleware\TwoFactorChallenge::class,