---
# System prepended metadata

title: 實作 Laravel 單 session 登入
tags: [開發經驗分享]

---

# 實作 Laravel 單 session 登入

限制登入人數為1，根據 [Single Session Login in Laravel](https://stackoverflow.com/questions/19510220/single-session-login-in-laravel) 大致有以下方法

1.檢查 session_id 是否改變

2.裝置或其他獨特 id，登入時刪除同使用者其他 session

3.內建

我用3，最簡單直觀

`LoginController`
```php
protected function authenticated()
{
    \Auth::logoutOtherDevices(request('password'));
}
```

`Kernel`
```php
\Illuminate\Session\Middleware\AuthenticateSession::class,
```

客製化寫法
```php
 public function login(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);

        $credentials = $request->only('email', 'password');

        if (\Auth::attempt($credentials)) {
            \Auth::logoutOtherDevices(request('password'));
            return redirect()->route('home');
        }

        return redirect("login")->withSuccess(' invalid credentials');
    }
```