Logout any user – Laravel, PHP, MySQL
In this article, we are going to teach you, how you can forcefully log out a user in your Laravel website using PHP and MySQL. Usually when users once logged in to your website, can only be logged out by clicking a logout button where we will log out the user using the Laravel Auth class.
But there will be a situation where you want to forcefully log out a specific user. At the end of this article, you will be able to do so.
Let’s get started
We assume that you already have a Laravel project up and running. You might have a users table and you might also have some user records saved in it.
First, you need to create a new column in your users table. That column will save the boolean value indicating whether the user has to be forcefully logged out or not ?
Add column in user’s table
Run the following command in your terminal at the root of your project:
php artisan make:migration add_column_force_logout_in_users_table
This will create a file named {time}_add_column_force_logout_in_users_table.php in “database/migrations” folder. Open that file and it will have the following content:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddColumnForceLogoutInUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// add a column wiht a data type 'boolean' with a default value 0
Schema::table('users', function (Blueprint $table) {
$table->boolean("force_logout")->after("password")->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
}
Now run the following command in your terminal to run this migration:
php artisan migrate
This will create a column named “force_logout” in your users table after the “password” column. Its data type will be boolean and its default value will be 0 which means FALSE.
You also need to add this column in your “App\Models\User.php” $fillable array, like this:
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
"force_logout", // add column in user model too
];
Now we need to create a controller (if you do not already have one). Run the following command in your terminal:
php artisan make:controller UsersController
This will create your controller in “app/Http/Controllers” folder with a file named “UsersController.php”. We will come back to this in a moment. First open your “routes/web.php” and create the following routes in it:
// include controller
use App\Http\Controllers\UsersController;
// called when the user is marked to be logged out forcefully
Route::post("/force-logout", [UsersController::class, "force_logout"]);
// to show all users
Route::get("/users", [UsersController::class, "users"]);
// user side home page
Route::get('/', [UsersController::class, "index"]);
Now open your UsersController class and first you need to include the Auth library and User model at the top.
// used to perform actions on logged in user
use Auth;
// get user model class
use App\Models\User;
Then we need to create a method to show all users.
// get all users
public function users()
{
// fetch all users sorted by newest to oldest with pagination
$users = User::orderBy("id", "desc")->paginate();
// render the page 'users' and pass the $users array in it
return view("users", [
"users" => $users
]);
}
Now create a file named “users.blade.php” in your “resources/views” folder. Write the following code in it:
<!-- table to display all users -->
<table>
<!-- table heading -->
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<!-- loop through all users -->
@foreach ($users as $user)
<tr>
<!-- show user name and email -->
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<!-- form which when submit will mark the user as to be forcefully log out -->
<form method="POST" action="{{ url('/force-logout') }}" onsubmit="return confirm('Are you sure you want to forcefully logout this user ?');">
<!-- CSRF protection token -->
{{ csrf_field() }}
<!-- user ID in a hidden input field, will be submitted with the form -->
<input type="hidden" name="id" value="{{ $user->id }}" required />
<!-- submit button -->
<input type="submit" value="Force Logout" />
</form>
</td>
</tr>
@endforeach
</table>
<!-- show pagination links -->
{{ $users->links() }}
<!-- minor stylings on the table -->
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
</style>
This will show the user name, email, and a button “Force Logout”. On clicking that button, it will ask for confirmation. Once confirmed, the form will be submitted. Now we need to handle this form submission.
Force logout any user you select
We already have the route for this, just need to create another method in your controller.
// mark user as to be logged out
public function force_logout()
{
// make sure the ID exists in users table
request()->validate([
"id" => "required|exists:users,id"
]);
// set the 'force_logout' column value as 1 of selected user
User::where("id", "=", request()->id)
->update([
"force_logout" => 1
]);
// redirect the user back to previous page
return redirect()->back();
}
This will first check if the user exists in the database. If yes, then it will update that user’s force_logout column value to 1 which means TRUE.
Finally, we need to log out the user if this column has a TRUE value. So create another method in your controller:
// home page for the user
public function index()
{
// check if user is logged in and is to be logged out forcefully
if (Auth::check() && Auth::user()->force_logout)
{
// since the user will be logged out now, set the value to 0 again
Auth::user()->force_logout = 0;
// update the 'force_logout' value in the database
Auth::user()->save();
// logout the user session
Auth::logout();
}
// display home page, Auth functions will not work now
return view("welcome");
}
You can write this code on your home page or in the constructor of your controller. The next time that the user accesses that page, he will be logged out.
If you face any problems following this, kindly let us know in the comments section below.