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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
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 $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
Lucky Media logo

Lucky Media

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

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Confidently Extract Single Array Items with Laravel's Arr::sole() Method image

Confidently Extract Single Array Items with Laravel's Arr::sole() Method

Read article
Safely Retry API calls in Laravel image

Safely Retry API calls in Laravel

Read article
Laravel's AsHtmlString Cast for Elegant HTML Attribute Management image

Laravel's AsHtmlString Cast for Elegant HTML Attribute Management

Read article
NativePHP for Mobile v1 — Launching May 2 image

NativePHP for Mobile v1 — Launching May 2

Read article
Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10 image

Map Eloquent Attributes into an Object Using the Collection Cast in Laravel 12.10

Read article
Converting Array Values to Enum Instances with Laravel's mapInto Method image

Converting Array Values to Enum Instances with Laravel's mapInto Method

Read article