Description
Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes!
Prepare bannable model
use Cog\Contracts\Ban\Bannable as BannableInterface;use Cog\Laravel\Ban\Traits\Bannable;use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements BannableInterface{ use Bannable;}
Prepare bannable model database table
Bannable model must have nullable timestamp column named banned_at. This value used as flag and simplify checks if user was banned. If you are trying to make default Laravel User model to be bannable you can use example below.
Create a new migration file
php artisan make:migration add_banned_at_column_to_users_table
Then insert the following code into migration file:
<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; return new class extends Migration{ public function up(): void { Schema::table('users', function (Blueprint $table) { $table->timestamp('banned_at')->nullable(); }); } public function down(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn('banned_at'); }); }};
Available methods
Apply ban for the entity
$user->ban();
Apply ban for the entity with reason comment
$user->ban([ 'comment' => 'Enjoy your ban!',]);
Apply ban for the entity which will be deleted over time
$user->ban([ 'expired_at' => '2086-03-28 00:00:00',]);
expired_at attribute could be \Carbon\Carbon instance or any string which could be parsed by \Carbon\Carbon::parse($string) method:
$user->ban([ 'expired_at' => '+1 month',]);
Remove ban from entity
$user->unban();
On unban all related ban models are soft deletes.
Check if entity is banned
$user->isBanned();
Check if entity is not banned
$user->isNotBanned();
Recent Courses on Laravel Daily
[NEW] Practical Laravel Security: Packages, Secrets, Supply-Chain Attacks
7 lessons
43 min read
Next.js Basics for Laravel Developers
11 lessons
58 min
Laravel 13 Eloquent: Expert Level
41 lessons
1 h 34 min