<?php
namespace App\Models;
use Cog\Contracts\Ban\Bannable as BannableContract;
use Cog\Laravel\Ban\Traits\Bannable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements BannableContract {
use HasApiTokens, HasFactory, Notifiable, Bannable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'banned_at'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function shouldApplyBannedAtScope() {
return true; //
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller {
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$users = User::get();
return view('users', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function ban(Request $request) {
$input = $request->all();
if (!empty($input['id'])) {
$user = User::find($input['id']);
$user->bans()->create([
'expired_at' => '+1 month',
'comment' => $request->baninfo,
]);
}
return redirect()->route('users.index')->with('success', 'Ban Successfully..');
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function revoke($id) {
if (!empty($id)) {
$user = User::find($id);
$user->unban();
}
return redirect()->route('users.index')
->with('success', 'User Revoke Successfully.');
}
}
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('users', [UserController::class, 'index'])->name('users.index');
Route::get('userUserRevoke/{id}', [UserController::class, 'revoke'])->name('users.revokeuser');
Route::post('userBan', [UserController::class, 'ban'])->name('users.ban');
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddBannedAtColumnToUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::table('users', function (Blueprint $table) {
$table->timestamp('banned_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('banned_at');
});
}
}
How to create ban/revoke user functionality in Laravel 5 example ?
By Hardik Savani June 14, 2017 Category : PHP Laravel Bootstrap jQuery MySqlPlayUnmuteLoaded: 1.20%FullscreenIn this tutorial, i am going to share with you how to create user block and unblock feature in your laravel 5 application using laravel-ban composer package.
It will mostly require to create user ban and revoke functionality for security reason. If you are developing big web application then it must be require to enable and disabled user when admin user want. Because some user make in-activity on our website then we could ban that user. So basicaly it is good if you are give user ban and revoke functionality to client on your laravel 5 application.
In this article, we will learn how to make ban and revoke functionality in laravel 5 application using laravel ban composer package. Laravel-ban package give us option to sent ban user for specific time and there are several things. It's interesting so we will create full example of user ban and revoke from scratch.
You have to just follow bellow step and you will get layout as like bellow:
Preview:
Step 1 : Install Laravel Application
This tutorial is from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration
In this step we have to make database configuration for example database name, username, password etc. So let's open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=here your database name(blog)DB_USERNAME=here database username(root)DB_PASSWORD=here database password(root)
After above command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create contactus table.
<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class AddBannedAtColumnToUsersTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->timestamp('banned_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('banned_at'); }); }}
Run migration by following command:
php artisan migrate
Now, we have to add Ban Class namespace on user model, So let's add User Model as like bellow:
app/User.php
<?phpnamespace App;use Cog\Ban\Contracts\HasBans as HasBansContract;use Cog\Ban\Traits\HasBans;use Illuminate\Notifications\Notifiable;use Illuminate\Foundation\Auth\User as Authenticatable;class User extends Authenticatable implements HasBansContract{ use Notifiable; use HasBans; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ];}
Step 6: Create Middleware
In this step we will create new custom middleware for check user is ban or not. They also provide default middleware but it not work as we want. So i simply create new and make it better. So let's create new middleware by following command:
<?phpnamespace App\Http\Middleware;use Closure;use Illuminate\Contracts\Auth\Guard;class ForbidBannedUserCustom{ /** * The Guard implementation. * * @var \Illuminate\Contracts\Auth\Guard */ protected $auth; /** * @param \Illuminate\Contracts\Auth\Guard $auth */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = $this->auth->user(); if ($user && $user->isBanned()) { \Session::flush(); return redirect('login')->withInput()->withErrors([ 'email' => 'This account is blocked.', ]); } return $next($request); }}
Now register middleware on Kernel file so let's add.
app/Http/Kernel.php
<?phpnamespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel{ ...... /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ .... 'is-ban' => \App\Http\Middleware\ForbidBannedUserCustom::class, ];}
Step 7: Add Route
In this is step we need to create route for users listing and ban/revoke. so open your routes/web.php file and add following route.
In this step we will have two controller Home and User Controller. In this file we will return view and ban revoke method So let's add code on both controller.
app/Http/Controllers/HomeController.php
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class HomeController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); }}
app/Http/Controllers/UserController.php
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\User;class UserController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { $users = User::get(); return view('users',compact('users')); } /** * Show the form for creating a new resource. * * @return Response */ public function ban(Request $request) { $input = $request->all(); if(!empty($input['id'])){ $user = User::find($input['id']); $user->bans()->create([ 'expired_at' => '+1 month', 'comment'=>$request->baninfo ]); } return redirect()->route('users.index')->with('success','Ban Successfully..'); } /** * Show the form for creating a new resource. * * @return Response */ public function revoke($id) { if(!empty($id)){ $user = User::find($id); $user->unban(); } return redirect()->route('users.index') ->with('success','User Revoke Successfully.'); }}
Step 9: Create View
In Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write code for listing and ban/revoke function jquery code,so put following code:
At last we will create new seeder and that way we can add some dummy user to users table. You can simply test everything. So let's run bellow comand to create seeder:
php artisan make:seeder UserTableSeeder
database/seeds/UserTableSeeder.php
<?phpuse Illuminate\Database\Seeder;use App\User;class UserTableSeeder extends Seeder{ /** * Run the database seeds. * * @return void */ public function run() { $users = [ ['name'=>'Admin', 'email'=>'admin@gmail.com','password'=>bcrypt('123456')], ['name'=>'User', 'email'=>'user@gmail.com','password'=>bcrypt('123456')], ['name'=>'Head', 'email'=>'head@gmail.com','password'=>bcrypt('123456')] ]; foreach ($users as $key => $value) { User::create($value); } }}
Run seeder be following command:
php artisan db:seed --class=UserTableSeeder
Now we are ready to run our example so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/
You can login by following username and password :