Skip to content

AdnanTech

Programming tutorials

Menu
  • Python
  • PHP
    • Laravel
    • WordPress
  • Javascript
    • React JS
    • Node.js
    • Vue JS
  • Databases
    • MySQL
    • MongoDB
  • Mobile apps
    • Android
    • iOS
  • Tutorials
    • Ticketing system
    • Chat app
  • Blog
  • Projects
  • API
    • Social network API
  • Services
    • Hash Generator
    • World Clock
    • Word Counter
    • Currency Converter
    • Financial Ledger
    • Time Difference
    • Stopwatch & Timer
    • Google Maps
  • SAAS
    • Job Entry

Logout any user – Laravel, PHP, MySQL

by adnanafzal565Posted onNovember 8, 2023November 8, 2023

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.

You can check this tutorial on YouTube as well, if you prefer a video based tutorial.

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.

Download our social networking site project developed in Laravel.

If you face any problems following this, kindly let us know in the comments section below.

Post Views: 1,462
Posted in PHPTagged laravel, login authentication, logout, php and mysql, session

Published by adnanafzal565

View all posts by adnanafzal565

Post navigation

Prev Instagram feed without API – PHP, MySQL
Next Dynamic pricing table – PHP, MySQL, and Vue JS

Recent Posts

  • SAAS in React + Laravel – Job Entry
  • Show selected images from input type file – React
  • Add dynamic rows in React
  • Soft Delete 🗑 – Node.js, MongoDB
  • 2 ways to loop through a number in React

Recent Comments

  1. canada pharmaceuticals online generic on PDF view in browser and export as file – PHP
  2. System on (no title)
  3. adnanafzal565 on (no title)
  4. adnanafzal565 on (no title)
  5. System on (no title)

Archives

  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • November 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • November 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020

Categories

  • Android
  • Complete Projects
  • CSS
  • FFmpeg
  • Git
  • htaccess
  • HTML
  • iOS
  • Javascript
  • Laravel
  • Leap Motion Controller
  • MEVN
  • MongoDB
  • MySQL
  • Node.js
  • PHP
  • Python
  • React JS
  • Swift
  • Tips & Tricks
  • Uncategorized
  • Vue JS
  • WordPress
AdnanTech © All rights reserved. 2013 - 2025
Looking for a web developer ?