透過Auth facade可以使用Laravel認證服務,利用attempt
方法來達成簡單的認證功能。
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/**
* 嘗試處理認證
*
* @param Request
* @return Response
*/
public function authenticate(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required']
]);
if (Auth::attempt($credentials) {
// 如果認證通過...
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => ['認證資料不匹配']
])
}
}
如果使用者的資料表有使用Laravel SoftDeletes(軟刪除)功能的話,可以在$credentials中加入deleted_at的條件,將執行軟刪除的使用者排除。
if (Auth::attempt([
'email' => $email,
'password' => $password,
'deleted_at' => null,
]))
按照上面的設定執行認證,能讓已執行軟刪除的使用者無法通過認證。
PHP Laravel:用auth的attempt方法來做認證時,如何加入軟刪除(deleted_at)條件
Laravel8+Vue3+Bootstrap5實作TODO List ep09:安裝bootstrap5並美化todo list畫面
Laravel8+Vue3+Bootstrap5實作TODO List ep07:安裝vue3跟基本設定
Laravel8+Vue3+Bootstrap5實作TODO List ep08:用vue重新製作todo list畫面
Laravel8+Vue3+Bootstrap5實作TODO List ep06:初步認識Web Route