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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
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
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Lucky Media logo

Lucky Media

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

Lucky Media
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
PhpStorm logo

PhpStorm

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

PhpStorm
Shift logo

Shift

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

Shift
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
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

The latest

View all →
Community Laravel Extension for Zed image

Community Laravel Extension for Zed

Read article
Advanced Eloquent Query Filtering with Filterable image

Advanced Eloquent Query Filtering with Filterable

Read article
Bulk Job Dispatching with Bus::bulk() in Laravel 13.13 image

Bulk Job Dispatching with Bus::bulk() in Laravel 13.13

Read article
Audit Laravel Apps for Security Issues with Checkpoint image

Audit Laravel Apps for Security Issues with Checkpoint

Read article
In-Memory Eloquent Models with Truffle image

In-Memory Eloquent Models with Truffle

Read article
Detect and Resolve Laravel Schema Drift with MigrAlign image

Detect and Resolve Laravel Schema Drift with MigrAlign

Read article