Block and Unblock User in Laravel Example Tutorial

Sep 01, 2022 . Admin

Hello Friends,

In this article we will cover on how to implement block and unblock user in laravel. This post will give you simple example of laravel user block unblock example. We will use laravel block user to login. I’m going to show you about how to ban. Let's see bellow example suspend or block user account in laravel.

It will mostly require creating user ban and revoking functionality for security reasons. If you are developing a big web application then it must be required to enable and disable user when the admin user wants. Because some user makes in-activity on our website then we could ban that user. So basically it is good if you give a user ban and revoke functionality to client on your laravel application.

In this article, we will learn how to make ban and revoke functionality in laravel application using laravel ban composer package. Laravel-ban package gives us the option to send ban user for a specific time and there are several things. It's interesting so we will create a full example of a user ban and revoke it from scratch.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

You have just to follow below step and you will get the layout as like bellow:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
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=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Laravel Auth

Laravel's laravel/ui package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:

composer require laravel/ui

Next, we need to generate auth scaffold with bootstrap, so let's run the below command:

php artisan ui bootstrap --auth

Then, install npm packages using the below command:

npm install

At last, built bootstrap CSS using the below command:

npm run dev
Step 4: Install package and configuration

In this step we have to laravel-ban package for user ban function so one your cmd or terminal and fire bellow command:

composer require cybercog/laravel-ban

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [
    ....
    Cog\Laravel\Ban\Providers\BanServiceProvider::class,
],
.....

we have to also make public configuration file by following command so run bellow command:

php artisan vendor:publish --provider="Cog\Laravel\Ban\Providers\BanServiceProvider" --tag="migrations"
php artisan migrate
Step 5: Add Migation and Model Config.

In this step we have to create another migration for add new column "banned_at" on users table. So let's create migration by following command:

php artisan make:migration add_banned_at_column_to_users_table

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.

<?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');
        });
    }
}

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/Models/User
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Cog\Contracts\Ban\Bannable as BannableContract;
use Cog\Laravel\Ban\Traits\Bannable;

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',
    ];

    /**
     * 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',
    ];
}
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:

php artisan make:middleware ForbidBannedUserCustom

Ok, now put bellow code on middleware file:

app/Http/Middleware/ForbidBannedUserCustom.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
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
<?php

namespace 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.

routes/web.php
<?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!
|
*/

Auth::routes();

Route::group(['middleware'=>'is-ban'], function(){

    Route::get('/home',[HomeController::class,'index'])->name('home');
    Route::get('users',[UserController::class,'index'])->name('users.index');
    Route::post('userBan',[UserController::class,'ban'])->name('users.ban');
    Route::get('userUserRevoke/{id}',[UserController::class,'revoke'])->name('users.revokeuser');

});

Step 8: Add Controller

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
<?php

namespace 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
&ly;?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Models\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:

resources/views/users.blade.php
@extends('layouts.app')
@section('content')

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>

<div class="container">
    <div class="row">
        <div class="col-md-12">

            @if(Session::has('success'))
                <div class="alert alert-success">
                    {{ Session::get('success') }}
                    @php
                    Session::forget('success');
                    @endphp
                </div>
            @endif

            <div class="card">
                <div class="card-header text-center">
                    <h1>Users Management</h1>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <tr>
                            <th>No</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Is Ban?</th>
                            <th>Action</th>
                        </tr>
                        @if($users->count())
                            @foreach($users as $key => $user)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $user->name }}</td>
                                    <td>{{ $user->email }}</td>
                                    <td>
                                        @if($user->isBanned())
                                        <label class="label label-danger">Yes</label>
                                        @else
                                        <label class="label label-success">No</label>
                                        @endif
                                    </td>
                                    <td>
                                        @if($user->isBanned())
                                        <a href="{{ route('users.revokeuser',$user->id) }}" class="btn btn-success btn-sm"> Revoke</a>
                                        @else
                                        <a class="btn btn-success ban btn-sm" data-id="{{ $user->id }}" data-action="{{ URL::route('users.ban') }}"> Ban</a>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        @endif
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $("body").on("click",".ban",function(){

        var current_object = $(this);

        bootbox.dialog({
            message: "<form class='form-inline add-to-ban' method='POST'><div class='form-group'><textarea class='form-control reason' rows='4' style='width:500px' placeholder='Add Reason for Ban this user.'></textarea></div></form>",
            title: "Add To Black List",
            buttons: {
                success: {
                label: "Submit",
                className: "btn-success",
                callback: function() {
                    var baninfo = $('.reason').val();
                    var token = $("input[name='_token']").val();
                    var action = current_object.attr('data-action');
                    var id = current_object.attr('data-id');


                    if(baninfo == ''){
                        $('.reason').css('border-color','red');
                        return false;
                    }else{
                        $('.add-to-ban').attr('action',action);
                        $('.add-to-ban').append('<input name="_token" type="hidden" value="'+ token +'">')
                        $('.add-to-ban').append('<input name="id" type="hidden" value="'+ id +'">')
                        $('.add-to-ban').append('<input name="baninfo" type="hidden" value="'+ baninfo +'">')
                        $('.add-to-ban').submit();
                    }
                }
            },
            danger: {
                label: "Cancel",
                className: "btn-danger",
                callback: function() {
                // remove
                }
            },
        }
    });
});
</script>
@endsection
Step 10: Create Seeder

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
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\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
Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/home

You can login by following username and password :

Email:admin@gmail.com

Password:123456

After login you have to open following url:

http://localhost:8000/users

I hope it can help you...

#Laravel