ka ern
ka ern

Reputation: 337

Make auto logout if the browser closed laravel

How to make auto logout when the user leaves the page in laravel 4.2. I use auth::atempt for login

Upvotes: 3

Views: 4407

Answers (2)

Iraj
Iraj

Reputation: 11

after days struggling with this subject finally found a way. we can use helpers to do this for example if you use session table for store sessions, you can do so: in session.php:

public function GetUsersId()
{
    return Session::whereNotNull('user_id')
        ->where('last_activity', '>=', now()->subMinutes(1))
        ->pluck('user_id');

}

this will give you the active users during last 1 minute. then in the helper file you can write:

if (!function_exists('SetUsersMode')) {
function SetUsersMode()
{
    $OnlineIds = (new App\Session)->GetUsersId();
    User::whereNotIn('id', $OnlineIds)->update(['Mode' => 'OFF']);
    User::whereIn('id', $OnlineIds)->update(['Mode' => 'ON']);
    return true;
}

} this will find all online users and set them online, also set the rest to offline. finally to use this helper, in your composesr.json file add the following line to autoload section:

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers.php"
    ],

now in your master layout blade file or any of controllers you can simply use it like:

@php
SetUsersMode();

@endphp

you can name function or helper whatever you want. this is the simplest way i found in couple days. hope this help somebody to speedup coding.

Upvotes: 1

Kalhan.Toress
Kalhan.Toress

Reputation: 21911

go to /app/config/session.php.

change

'expire_on_close' => false,

to

 'expire_on_close' => true,

Upvotes: 5

Related Questions