Jump24 - Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Implementing Account Suspension in Laravel

Last updated on by

Implementing Account Suspension in Laravel image

Account suspension is a common requirement in web applications to restrict user access Permanently or Temporarily. Laravel provides a flexible way to implement this feature using database fields, middleware, and scheduled tasks. This guide covers both Permanent and Temporary Suspensions.

Permanent Suspension

A Permanently Suspended user is blocked from accessing the application until manually unsuspended.

1. Add a Suspension Field to the Users Table

To track whether a user is suspended, add a suspended_at column to the users table:

Schema::table('users', function (Blueprint $table) {
    $table->timestamp('suspended_at')->nullable();
});

2. Update the User Model

Define a method in the User model to check if the user is suspended:

class User extends Authenticatable
{
    public function suspended(): bool
    {
        return !is_null($this->suspended_at);
    }
}

3. Middleware to Restrict Suspended Users

To block access for suspended users, create a middleware CheckSuspended:

public function handle(Request $request, Closure $next)
 
{
    if (auth()->check() && auth()->user()->suspended()) {
        abort(403, 'Your account is suspended.');
    }
 
    return $next($request);
}

4. Suspending and Unsuspending Users

Implement functions in a controller to suspend and unsuspend users:

public function suspend(User $user)
{
$user->update([
'suspended_at' => Carbon::now(),
]);
 
return response()->json(['message' => 'User suspended successfully.']);
 
}
 
public function unsuspend(User $user)
 
{
$user->update([
'suspended_at' => null,
]);
 
return response()->json(['message' => 'User unsuspended successfully.']);
}

Temporary suspension

For Temporary Suspensions, we store a suspended_until timestamp instead of suspended_at to allow automatic reactivation.

1. Modify the Users Table

Add a suspended_until column:

Schema::table('users', function (Blueprint $table) {
    $table->timestamp('suspended_until')->nullable();
});

2. Update the User Model

Modify the suspended() method to check if the suspension is still active:

class User extends Authenticatable
{
    public function suspended(): bool
    {
        return !is_null($this->suspended_until) && Carbon::now()->lessThan($this->suspended_until);
    }
}

3. Middleware to Restrict Suspended Users

It is the same as before, but now it checks the suspended_until field:

public function handle(Request $request, Closure $next)
{
    if (auth()->check() && auth()->user()->suspended()) {
        abort(403, 'Your account is suspended.');
    }
 
    return $next($request);
}

4. Suspending and Unsuspending Users Temporarily

Set a future timestamp for Temporary Suspensions:

public function suspend(User $user)
{
    $user->update([
        'suspended_until' => Carbon::now()->addDays(7),
    ]);
 
    return response()->json(['message' => 'User suspended for 7 days.']);
 
}
 
public function unsuspend(User $user)
{
    $user->update([
        'suspended_until' => null,
    ]);
 
    return response()->json(['message' => 'User unsuspended successfully.']);
}

5. Auto-Unsuspend Users via Scheduler

Since Temporary Suspensions expire automatically, we can use a scheduled task to lift expired suspensions:

namespace App\Console\Commands;
 
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
 
class SuspendClear extends Command
{
    /**
     * The name and signature of the console command.
     */
 
    protected $signature = 'suspend:clear';
 
    /**
     * The console command description.
     */
 
    protected $description = 'Automatically lift expired suspensions';
 
    /**
     * Execute the console command.
     */
    public function handle()
    {
        User::whereNotNull('suspended_until')
            ->where('suspended_until', '<=', Carbon::now())
            ->update([
                'suspended_until' => null,
            ]);
    }
}

Add this the suspend:clear command to the scheduler to run hourly, within the routes/console.php file:

/**
 * php artisan schedule:work
 */
Schedule::command('suspend:clear')->hourly();

Conclusion

This guide demonstrates how to implement permanent and temporary account suspensions in Laravel using:

  • Database columns (suspended_at or suspended_until).
  • Middleware to restrict access.
  • Controller methods for managing suspensions.
  • A scheduled task to auto-lift suspensions.

By integrating these steps, you can effectively manage user access and ensure compliance with your application's policies.

Ahmed Alaa photo

Backend web developer and author in Laravel. Experienced in building scalable applications, contributing to open-source projects, and optimizing performance.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Browse and Execute Artisan Commands from an Interactive TUI image

Browse and Execute Artisan Commands from an Interactive TUI

Read article
Laravel Pint Now Replaces Fully Qualified Class Names with Imports image

Laravel Pint Now Replaces Fully Qualified Class Names with Imports

Read article
Inertia v3 Upgrade Prompt and JSON Log Support in Laravel Boost v2.3.0 image

Inertia v3 Upgrade Prompt and JSON Log Support in Laravel Boost v2.3.0

Read article
Laracon AU Returns to Brisbane - Call for Speakers Now Open image

Laracon AU Returns to Brisbane - Call for Speakers Now Open

Read article
Detecting and Fixing Race Conditions in Laravel Applications image

Detecting and Fixing Race Conditions in Laravel Applications

Read article
LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI image

LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI

Read article