Laravel User Ban/Revoke Functionality

AuthorSumit Dey Sarkar

Pubish Date26 Jan 2024

categoryLaravel

In this tutorial, we will learn Laravel User Ban/Revoke Functionality.

Laravel User Ban/Revoke Functionality

How to Ban/Suspend Users in Laravel Project

In Laravel, you can implement user ban or revoke functionality by using the built-in features like middleware, Eloquent models, and routes.

Let's follow the below steps -

Step 1: Add a is_banned column to the users table

Open your migration file for the users table and add a boolean column named is_banned:

// In a migration file
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('is_banned')->default(false);
    });
}

Run the migration:

php artisan migrate

Step 2: Create Middleware

Create a middleware that will check if a user is banned before allowing access to specific routes.

php artisan make:middleware CheckUserBan

In CheckUserBan.php middleware file, you can implement the logic like this:

// app/Http/Middleware/CheckUserBan.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckUserBan
{
    public function handle(Request $request, Closure $next)
    {
        if (auth()->check() && auth()->user()->is_banned) {
            // User is banned, redirect or respond accordingly
            return redirect()->route('banned');
        }

        return $next($request);
    }
}

Step 3: Register the Middleware

Register the middleware in the Kernel.php file:

// app/Http/Kernel.php

protected $routeMiddleware = [
    // ...
    'checkUserBan' => \App\Http\Middleware\CheckUserBan::class,
];

Step 4: Apply Middleware to Routes

Apply the checkUserBan middleware to the routes you want to protect:

// web.php or routes.php

Route::group(['middleware' => 'checkUserBan'], function () {
    // Your protected routes go here
    Route::get('/dashboard', 'DashboardController@index')->name('dashboard');
});

// Optionally, create a route for banned users
Route::get('/banned', function () {
    return view('banned');
})->name('banned');

Step 5: Create the Banned View

Create a view for the banned users (resources/views/banned.blade.php):

<!DOCTYPE html>
<html>
<head>
    <title>Banned</title>
</head>
<body>
    <h1>Sorry, you are banned!</h1>
</body>
</html>

Now, when a user is banned, they will be redirected to the 'banned' route or view.

Step 6: Banning/Revoking Users

You can update a user's is_banned field based on your application logic:

// Banning a user
$user = User::find($userId);
$user->update(['is_banned' => true]);

// Revoking ban for a user
$user = User::find($userId);
$user->update(['is_banned' => false]);

You can enhance the middleware to handle more advanced scenarios or use roles and permissions for a more flexible solution.

Comments 0

Leave a comment