
Block/un-block user in Laravel
In this tutorial, you will learn how you can add block/un-block feature in your Laravel website. First, we will display all users in a list to admin panel. In front of each user, we will display a button either to block or un-block the user.
Display users list
First, you need to create a route in your routes/web.php:
// routes/web.php
Route::get("/users", [UserController::class, "users"]);
Then we need to create this method in our controller:
// app/Http/Controllers/UserController.php
public function users()
{
$users = DB::table("users")
->orderBy("id", "desc")
->paginate();
return view("users", [
"users" => $users
]);
}
In this method, we are fetching all the users from database and passing that into a view. Then we need to create that view and display the users.
<!-- resources/views/users.blade.php -->
<table>
<thead>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@if (count($users) <= 0)
<tr>
<td colspan="2">No user found.</td>
</tr>
@endif
@foreach ($users as $user)
<tr>
<td>{{ $user->name ?? "" }}</td>
<td>
@if ($user->is_block)
<button type="button" onclick="unBlockUser(event, '{{ $user->id }}', '{{ $user->name }}');">Un-block</button>
@else
<button type="button" onclick="blockUser(event, '{{ $user->id }}', '{{ $user->name }}');">Block</button>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
If no user is found, then we will display a message. This will pass the user ID and name to the function. We need the user ID in the AJAX request and username to display it to the admin for confirmation.
Block/un-block user
You need to create a column “is_block” in your “users” table. So you need to change your migration like this:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->enum("type", ["user", "admin"]);
$table->boolean("is_block")->default(0);
$table->rememberToken();
$table->timestamps();
});
After that, you need to run your migration. So run the following command in your terminal at the root of your project:
php artisan migrate
If you check in your database, you will see that a new column has been created in “users” table. It can have only 2 values 0 or 1. Now, back to your blade view, you need to create a Javascript function that will be called when user clicked the block button.
// resources/views/users.blade.php
async function blockUser(event, id, name) {
const node = event.currentTarget;
if (confirm("Are you sure you want to block '" + name + "' ?")) {
node.setAttribute("disabled", "disabled");
const formData = new FormData();
formData.append("id", id);
try {
const response = await axios.post(
baseUrl + "/users/block",
formData
);
if (response.data.status == "success") {
window.location.reload();
} else {
alert(response.data.message);
}
} catch (exp) {
alert(exp.message);
} finally {
node.removeAttribute("disabled");
}
}
}
It is first asking for confirmation from admin. Once confirmed, it calls an AJAX request and pass the user ID to it. If the request is successfully, it will reload the page. Otherwise, it will display an error message in an alert dialog. It will also make the “Block” button disabled until the AJAX request is complete.
After that, we need to create a route that will handle this request.
// routes/web.php
Route::post("/users/block", [UserController::class, "block"]);
Then we need to create that method in our controller.
// app/Http/Controllers/UserController.php
use DB;
use Validator;
public function block()
{
$validator = Validator::make(request()->all(), [
"id" => "required"
]);
if ($validator->fails())
{
return response()->json([
"status" => "error",
"message" => $validator->errors()->first()
]);
}
$id = request()->id ?? 0;
$user = DB::table("users")
->where("id", "=", $id)
->first();
if ($user == null)
{
return response()->json([
"status" => "error",
"message" => "User not found."
]);
}
DB::table("users")
->where("id", "=", $user->id)
->update([
"is_block" => 1,
"updated_at" => now()->utc()
]);
return response()->json([
"status" => "success",
"message" => "User has been blocked."
]);
}
In this method, we are first making sure that the ID is provided and the user exists in database. Then we are simply setting the “is_block” column value of that user to 1. We are also updating the timestamp so we can know when user was blocked or un-blocked.
If you try now and click the “Block” button and check in your phpMyAdmin, you will see that the “is_block” column value of that user becomes 1.
The un-block feature is almost similar to this one. You just need to change the “is_block” value to 0.
DB::table("users")
->where("id", "=", $user->id)
->update([
"is_block" => 0,
"updated_at" => now()->utc()
]);
Now that we can flip the “is_block” bit to 0 and 1. Let me show you how you can protect your routes from users who are blocked.
Middleware for protected routes
In order to create a middleware, we will run the following command in our terminal:
php artisan make:middleware UserAuth
This will create a file named “UserAuth.php” in folder “app\Http\Middleware”. Following should be the content of that file:
<?php
// app\Http\Middleware\UserAuth.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Auth;
class UserAuth
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (Auth::check())
{
if (Auth::user()->is_block)
{
abort(403, "You have been blocked.");
}
return $next($request);
}
abort(401);
}
}
Middleware sits between client request and server’s handler function. So we will wrap the routes with this middleware whom we want to protect.
// routes/web.php
use App\Http\Middleware\UserAuth;
Route::group([
"middleware" => [UserAuth::class]
], function () {
Route::get("/protected-route", [UserController::class, "protected_route"]);
});
Now user will be able to access that route only if he is logged-in and is not blocked. He will not be able to access it, if he is either not logged-in or if he is blocked.
So this is how you can create a block/un-block feature in your Laravel website. If you face any problem in following this, kindly do let me know.