{"id":1566,"date":"2024-09-10T16:19:54","date_gmt":"2024-09-10T16:19:54","guid":{"rendered":"https:\/\/debugspot.com\/?p=1566"},"modified":"2024-09-10T16:54:51","modified_gmt":"2024-09-10T16:54:51","slug":"log-out-users-from-other-devices-in-laravel-11","status":"publish","type":"post","link":"https:\/\/debugspot.com\/blogs\/log-out-users-from-other-devices-in-laravel-11\/","title":{"rendered":"Effortlessly Log Out Users from Other Devices in Laravel 11 \u2013 Ultimate Guide"},"content":{"rendered":"<p>Learn how to log out users from other devices in Laravel 11 using middleware and Auth methods. Ensure secure session management by automatically logging out from all other devices, keeping the current session active.<\/p>\n<p>In this article, we&#8217;ll explore how to log out users from other devices in Laravel 11. We&#8217;ll guide you through the process of ensuring that a user is only logged in on one device at a time. This feature is particularly useful when you want to log out sessions on all other devices while keeping the current device authenticated\u2014like when a user updates their password. Let&#8217;s dive into implementing automatic logout across multiple devices in Laravel 11.<\/p>\n<h3 class=\"wp-block-heading\">Step 1: Add the Middleware<\/h3>\n<p>To start, we need to configure Laravel 11 to use the AuthenticateSession middleware. This middleware ensures that user sessions are properly authenticated across multiple devices, logging out sessions on other devices if necessary.<\/p>\n<p>For Laravel 11<\/p>\n<p>In bootstrap\/app.php, we\u2019ll configure the application to include the middleware:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nuse Illuminate\\Foundation\\Application;\r\n  use Illuminate\\Foundation\\Configuration\\Exceptions;\r\n  use Illuminate\\Foundation\\Configuration\\Middleware;\r\n\r\n  return Application::configure(basePath: dirname(__DIR__))\r\n    ->withRouting(\r\n        web: __DIR__.'\/..\/routes\/web.php',\r\n        commands: __DIR__.'\/..\/routes\/console.php',\r\n        health: '\/up',\r\n    )\r\n    ->withMiddleware(function (Middleware $middleware) {\r\n        $middleware->alias([\r\n            'auth.session' => \\Illuminate\\Session\\Middleware\\AuthenticateSession::class,\r\n        ]);\r\n    })\r\n    ->withExceptions(function (Exceptions $exceptions) {\r\n        \/\/\r\n    })->create();\r\n <\/code><\/pre>\n<p>For Laravel 8, 9, and 10    <\/p>\n<p>If you\u2019re working with Laravel 8, 9, or 10, you only need to enable the AuthenticateSession middleware in app\/Http\/Kernel.php: <\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\"> \r\n protected $middlewareGroups = [\r\n  'web' => [\r\n      \\App\\Http\\Middleware\\EncryptCookies::class,\r\n      \\Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::class,\r\n      \\Illuminate\\Session\\Middleware\\StartSession::class,\r\n      \\Illuminate\\Session\\Middleware\\AuthenticateSession::class, \/\/ Ensure this line is uncommented\r\n      \\Illuminate\\View\\Middleware\\ShareErrorsFromSession::class,\r\n      \\App\\Http\\Middleware\\VerifyCsrfToken::class,\r\n      \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\r\n  ],\r\n\r\n  \/\/ Other middleware groups...\r\n  ];     \r\n<\/code><\/pre>\n<h3 class=\"wp-block-heading\">Step 2: Add Middleware to Routes<\/h3>\n<p>Next, apply the auth.session middleware to your routes to ensure the middleware is active for the routes you want to secure.<\/p>\n<p>You can add this middleware to a route group as shown below:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\n  Route::middleware(['auth', 'auth.session'])->group(function () {\r\n    Route::get('\/', function () {\r\n        \/\/ Your route logic here\r\n    });\r\n    \/\/ Add more routes as needed\r\n  });\r\n <\/code><\/pre>\n<h3 class=\"wp-block-heading\">Step 3: Implement the logoutOtherDevices Method<\/h3>\n<p>Laravel provides the logoutOtherDevices method in the Auth facade to log out sessions on other devices. This is particularly useful when a user changes their password or when enforcing a security policy.<\/p>\n<p><b>1. Update the login Method in Your Login Controller        <\/b><\/p>\n<p>Modify the login method to include the logoutOtherDevices method:        <\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">\r\nuse Illuminate\\Support\\Facades\\Auth;\r\n\r\n  public function login(LoginRequest $request)\r\n  {\r\n      $credentials = $request->getCredentials();\r\n  \r\n      if (!Auth::validate($credentials)) {\r\n          return redirect()->to('login')\r\n              ->withErrors(trans('auth.failed'));\r\n      }\r\n  \r\n      $user = Auth::getProvider()->retrieveByCredentials($credentials);\r\n  \r\n      Auth::login($user, $request->get('remember'));\r\n  \r\n      if ($request->get('remember')) {\r\n          $this->setRememberMeExpiration($user);\r\n      }\r\n  \r\n      return $this->authenticated($request, $user);\r\n  }\r\n  \r\n  protected function authenticated(Request $request, $user)\r\n  {\r\n      Auth::logoutOtherDevices($request->get('password'));\r\n  \r\n      return redirect()->intended();\r\n  }\r\n<\/code><\/pre>\n<p><b>2. How It Works  <\/b><\/p>\n<p>When Auth::logoutOtherDevices($request->get(&#8216;password&#8217;)) is called, Laravel invalidates all other sessions for the user. This means the user will be logged out from all devices except the one they\u2019re currently using.<\/p>\n<p>For more detail you can write <a href=\"https:\/\/laravel.com\/docs\/11.x\/authentication\" target=\"_blank\" rel=\"noopener\">Laravel Documentation<\/a><\/p>\n<h3 class=\"wp-block-heading\">Summary<\/h3>\n<p>In this blog post, we explore how to log out users from other devices in Laravel 11, ensuring that a user is only logged in on one device at a time. This is especially useful when a user updates their password or you want to enhance security by logging out sessions on all other devices while keeping the current session active. We begin by adding the AuthenticateSession middleware to manage user sessions across devices. Then, we apply this middleware to specific routes for security. Finally, we implement the logoutOtherDevices method, which allows Laravel to invalidate all other active sessions, logging out users from other devices except the one they are currently using. This approach ensures a more secure and controlled session management system in Laravel 11.<\/p>\n<h5>You may also find interesting:<\/h5>\n<p><a title=\"Laravel Scout in Laravel 11: A Comprehensive Tutorial with Example\" href=\"https:\/\/debugspot.com\/blogs\/integrate-google-calendar-with-laravel\/\" target=\"_blank\" rel=\"noopener\">Laravel Scout in Laravel 11: A Comprehensive Tutorial with Example<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to log out users from other devices in Laravel 11 using middleware and Auth methods. Ensure secure session management by automatically logging out from all other devices, keeping the current session active. In this article, we&#8217;ll explore how to log out users from other devices in Laravel 11. We&#8217;ll guide you through the process of ensuring that a user is only logged in on one device at a time. This feature is particularly useful when you want to log out sessions on all other devices while keeping the current device authenticated\u2014like when a user updates their password. Let&#8217;s dive into implementing automatic logout across multiple devices in Laravel 11. Step 1: Add the Middleware To start, we need to configure Laravel 11 to use the AuthenticateSession middleware. This middleware ensures that user sessions are properly authenticated across multiple devices, logging out sessions on other devices if necessary. For Laravel 11 In bootstrap\/app.php, we\u2019ll configure the application to include the middleware: use Illuminate\\Foundation\\Application; use Illuminate\\Foundation\\Configuration\\Exceptions; use Illuminate\\Foundation\\Configuration\\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.&#8217;\/..\/routes\/web.php&#8217;, commands: __DIR__.&#8217;\/..\/routes\/console.php&#8217;, health: &#8216;\/up&#8217;, ) ->withMiddleware(function (Middleware $middleware) { $middleware->alias([ &#8216;auth.session&#8217; => \\Illuminate\\Session\\Middleware\\AuthenticateSession::class, ]); }) ->withExceptions(function (Exceptions $exceptions) { \/\/ })->create(); For Laravel 8, 9, and &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"rank_math_lock_modified_date":false,"footnotes":""},"categories":[3],"tags":[46,54,53],"class_list":["post-1566","post","type-post","status-publish","format-standard","hentry","category-laravel","tag-laravel","tag-laravel-scout","tag-laravel11"],"acf":[],"_links":{"self":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1566"}],"collection":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/comments?post=1566"}],"version-history":[{"count":8,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1566\/revisions"}],"predecessor-version":[{"id":1569,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1566\/revisions\/1569"}],"wp:attachment":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/media?parent=1566"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/categories?post=1566"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/tags?post=1566"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}