
Bug编译狮
在 Laravel 中实现密码登录通常涉及以下几个步骤:
-
创建用户模型和迁移: 首先,你需要为用户表创建模型和迁移文件。
php artisan make:model User然后编辑
User模型,并添加必要的字段(例如email和password)。// app/Models/User.php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateFoundationAuthUser as Authenticatable; class User extends Authenticatable { use HasFactory; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }创建迁移文件:
php artisan make:migration create_users_table --create=users编辑生成的迁移文件并添加
email和password字段。// database/migrations/2023_04_01_000000_create_users_table.php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } } -
运行迁移: 运行数据库迁移以创建用户表。
php artisan migrate -
配置认证系统: 打开
config/auth.php文件,并确保以下配置正确:// config/auth.php return [ 'defaults' => [ 'guard' => 'web', 'api' => 'api', ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => AppModelsUser::class, ], ], 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], ]; -
创建控制器: 创建一个控制器来处理登录逻辑。
php artisan make:controller AuthController编辑
AuthController控制器并添加登录方法。// app/Http/Controllers/AuthController.php namespace AppHttpControllers; use AppModelsUser; use IlluminateHttpRequest; use IlluminateSupportFacadesHash; class AuthController extends Controller { public function login(Request $request) { $credentials = $request->only(['email', 'password']); if ($user = User::where('email', $credentials['email'])->first()) { if (Hash::check($credentials['password'], $user->password)) { auth()->login($user); return redirect()->intended('/'); } else { return back()->withErrors(['password' => 'The provided password is incorrect.']); } } else { return back()->withErrors(['email' => 'The provided email does not exist.']); } } } -
创建路由: 在
routes/web.php文件中定义登录路由。// routes/web.php use AppHttpControllersAuthController; use IlluminateSupportFacadesRoute; Route::get('/login', [AuthController::class, 'login'])->name('login'); Route::post('/login', [AuthController::class, 'login'])->name('login.post'); -
创建登录表单: 创建一个简单的 HTML 表单来提交登录请求。
<!-- resources/views/login.blade.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h1>Login</h1> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('login.post') }}" method="POST"> @csrf <label for="email">Email:</label> <input type="email" id="email" name="email" required><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br><br> <button type="submit">Login</button> </form> </body> </html>
通过以上步骤,你可以在 Laravel 中实现基本的密码登录功能。如果你需要更复杂的登录逻辑或安全措施,请参考 Laravel 的官方文档。

黑板Bug讲师
介绍
Laravel 是一个强大的且受欢迎的PHP框架,用于Web 应用程序开发。它提供了构建安全且可扩展 Web 应用程序所需的强大功能。Laravel 提供了一个无缝的身份验证系统。在本教程中,我们将从头开始探索如何实现 Laravel 中的基本身份验证系统。我们首先会探讨基础概念,逐步深入更高级的概念,包括表单验证、密码哈希和认证中间件。
先决条件
在开始之前,请确保您已经安装了以下软件:
一个工作数据库设置(如 MySQL、PostgreSQL、SQLite 等)
作曲家
PHP 7.3 或者更高版本
推荐使用 Laravel 8.0 或更高版本。
注意:本指南假设您对Laravel和MVC架构有基本的理解。
设置身份验证框架
Laravel 提供了一个方便的命令来设置身份验证框架。使用内置的命令行工具 Artisan 来创建必要的控制器、视图和路由:
php artisan ui bootstrap --auth
该命令将生成基本登录和注册系统的视图、路由和控制器所需的内容。要编译前端资产,请运行以下命令:
npm install
npm run dev
请配置您的 .env 文件以连接到数据库,并然后迁移默认用户表:
php artisan migrate
创建登录路由。
在完成身份验证框架后,登录路由将在‘routes/web.php’文件内定义。
Auth::routes();
访问“/login”以查看Laravel提供的默认登录表单。该表单由“AppHttpControllersAuthLoginController”后端控制器支持。
理解登录控制器(LoginController)
Laravel的LoginController负责处理登录请求。你可以重写authenticate方法,这是通常用来定制登录行为的地方。下面是默认的方法:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
当用户提交登录表单时,上述的authenticate方法会被触发。Auth::attempt 是Laravel内置的一个函数,用于验证用户凭证是否与数据库中的记录匹配。如果认证成功,用户会被重定向到目标页面,通常就是仪表板。
验证输入数据
数据验证在任何登录系统中都至关重要。Laravel的“Request”类提供了“validate”方法,您可以使用它来应用输入验证规则。请修改“authenticate”函数以包含验证规则:
public function authenticate(Request $request)
{
// Validate the form data
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
// Authenticate the user
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
// Authentication failed...
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
该方法抛出一个异常,会将用户重定向回带有验证错误的表单。
密码哈希和安全性
Laravel自带内置的哈希支持,你应该始终使用它来处理密码。默认情况下,Laravel 使用bcrypt哈希算法。在注册用户时,请确保他们的密码已进行哈希处理。
$user = User::create([
'name' => $request->name,
'email' => $request->email,
// Use the Hash facade to secure the password
'password' => Hash::make($request->password),
]);
不要在数据库中存储明文密码。Laravel的User模型在设置password属性时会自动对密码进行哈希处理,假设你使用的是IlluminateSupportFacadesHash类。
高级:自定义身份验证守卫
Laravel的身份验证系统非常灵活,允许您定义自定义的守护程序。守护程序定义用户对每个请求进行身份验证的方式。例如,您可以为您的网站管理员或API用户提供一个单独的守护程序。
为了创建自定义的守护者,你需要在 config/auth.php 文件中进行定义,并且通常还会创建一个自定义的提供者。以下是一个自定义守护者的配置示例:
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => AppModelsAdmin::class,
],
],
为了通过自定义的检查点进行身份验证,可以使用以下方法:
if (Auth::guard('admin')->attempt($credentials)) {
// Admin authentication passed...
}
集成中间件
使用 –auth 选项设置身份验证时,会自动为您的路由应用 auth 中间件: Laravel 中间件确保只有认证用户才能访问某些路由。中间件可以重定向访客到登录页面并保护路由。 ‘auth’ 中间件会在使用 –auth 参数设置身份验证时自动应用于您的路由:
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
});
任何试图通过访客访问‘/dashboard’的尝试都会被重定向到登录页面。
结论。
我们已经讨论了如何在Laravel中实现密码登录系统。从基本的认证框架设置开始,我们探讨了自定义化和安全实践,如输入验证和密码哈希。Laravel的auth系统的灵活性允许处理复杂的场景,包括自定义守护程序和中间件。有了这些技能,你现在可以为你的Laravel应用实施强大的认证功能。

长工码奴1523
Laravel 是一个非常流行的 PHP 开发框架,它提供了丰富的功能和强大的安全性特性。下面我将向您介绍如何在 Laravel 中实现简单的密码登录。
步骤 1: 创建一个新的控制器
首先,我们需要创建一个新的控制器来处理用户认证。我们将使用 Auth 类别作为基础,并扩展它以提供我们的逻辑。
<?php
namespace AppHttpControllers;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
class AuthController extends Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
步骤 2: 实现登录路由
接下来,我们为登录页面添加一个路由。我们将使用 Route::get() 函数来设置一个 GET 请求的路由。
<?php
// app/Http/routes.php
Route::group(['prefix' => 'auth'], function () {
Route::post('/login', 'AuthController@login')->name('login');
Route::post('/logout', 'AuthController@logout')->name('logout');
});
步骤 3: 实现登录验证逻辑
在 AuthController.php 文件中,我们将实现登录验证逻辑。这个逻辑包括验证用户名和密码是否正确。
<?php
namespace AppHttpControllers;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
class AuthController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* 登录用户的逻辑。
*
* @param array $credentials
* @return bool
*/
protected function login(array $credentials)
{
// 在这里添加实际的身份验证逻辑
if (Auth::attempt($credentials)) {
return true;
}
return false;
}
/**
* 用户登出的逻辑。
*
* @return mixed
*/
protected function logout()
{
Auth::logout();
return redirect()->route('login');
}
}
步骤 4: 使用 Laravel 的身份验证库
最后一步是启用 Laravel 的身份验证库。这样,您的应用程序就可以安全地存储和检索用户的凭据了。
composer require laravelcollective/html
现在,您可以使用以下命令激活身份验证:
php artisan config:cache
这将在您的 .env 文件中保存配置信息,然后您可以在应用中使用 Auth::guard() 方法获取用户身份。
示例代码
以下是完整的示例代码,展示了如何在 Laravel 中实现密码登录。
<?php
namespace AppHttpControllers;
use IlluminateFoundationBusDispatchesJobs;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;
use IlluminateFoundationAuthAccessAuthorizesRequests;
use IlluminateSupportFacadesHash;
class AuthController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* 登录用户的逻辑。
*
* @param array $credentials
* @return bool
*/
protected function login(array $credentials)
{
$user = User::where('email', $credentials['email'])->first();
if (!$user || ! Hash::check($credentials['password'], $user->password)) {
return response()->json([
'error' => 'Invalid credentials'
], 400);
}
return true;
}
/**
* 用户登出的逻辑。
*
* @return mixed
*/
protected function logout()
{
auth()->logout();
return redirect()->route('login');
}
}
在这个例子中,我们定义了一个名为 User 的模型类,其中包含了用户的电子邮件和密码字段。请注意,你需要根据实际情况替换这些字段名。
