Outsource Laravel Development Partner - $3200/Month | Bacancy

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
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
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
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 →
Install Laravel Package Guidelines and Skills in Boost image

Install Laravel Package Guidelines and Skills in Boost

Read article
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article