簡體   English   中英

如何在Laravel中手動登錄用戶?

[英]How can I login the user manually in Laravel?

這是我的代碼:

public function register_and_login(Request $request)
{
    $this->validator_short($request->all())->validate();

    $user = User::where('cell_phone', $request->cell_phone)->first();

    // already registered
    if ( is_null($user) ) {
        $user_id = User::create([
                    'name' => $request->name,
                    'cell_phone' => $request->cell_phone,
                    'password' => bcrypt($request->password),
        ]);
    } else {
        $user_id = $user->id;
    }

    $this->guard()->login($user_id);

    dd('user is logged in now');
}

我的代碼在用戶尚未注冊時起作用,我們創建了它。 但是,當他已經注冊時,我的代碼將引發以下錯誤:

在此處輸入圖片說明

我該如何解決?

確保User模型擴展了Authenticatable

use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable

另外,請使用auth()幫助程序或Auth:: facade:

$user = User::create(['name' => $request->name,
    'cell_phone' => $request->cell_phone,
    'password' => bcrypt($request->password)
]);
auth()->login($user);

https://laravel.com/docs/5.5/authentication#other-authentication-methods

將您的其他部分更改為-

else {
    $user_id = $user;
}

登錄功能不要求您輸入整數ID,而是要求提供Authenticable。 在任何默認的Laravel應用程序中,通常是用戶模型。

問題出在您的else語句中。 檢查單元號時,無需將$ user_id設置為您加載的用戶的ID。 您只需要使用您加載的用戶。 根據您的邏輯,您甚至不需要else語句。

您的邏輯可能存在一個單獨的問題,即您正在檢查是否存在該單元號,如果存在,則登錄用戶,而不是進行檢查的用戶。 這可能是理想的行為,但似乎並非如此。

public function register_and_login(Request $request)
{
  $this->validator_short($request->all())->validate();

  $user = User::where('cell_phone', $request->cell_phone)->first();

  // already registered
  if ( is_null($user) ) {
    $user = User::create([
                'name' => $request->name,
                'cell_phone' => $request->cell_phone,
                'password' => bcrypt($request->password),
    ]);
  }

 $this->guard()->login($user);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM