larvel 账号登录功能
时间: 2023-09-12 10:10:19 浏览: 54
Laravel 提供了很方便的身份验证系统来实现账号登录功能。这里简单介绍一下如何实现。
1. 创建用户表
在数据库中创建一个用户表,可以使用以下命令来创建:
```
php artisan make:model User -m
```
这个命令将会创建一个 `User` 模型以及迁移文件。打开迁移文件,在 `up` 方法中添加如下代码:
```php
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();
});
```
然后运行迁移:
```
php artisan migrate
```
2. 创建登录控制器
使用以下命令来创建一个登录控制器:
```
php artisan make:controller AuthController
```
在控制器中添加以下方法:
```php
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
```
`showLoginForm` 方法返回登录表单视图,`login` 方法用于验证用户输入的邮箱和密码是否正确,如果正确就登录用户并重定向到指定页面,否则返回错误信息。
3. 创建登录表单视图
在 `resources/views/auth` 目录下创建一个名为 `login.blade.php` 的视图文件,添加以下代码:
```html
<form method="POST" action="{{ route('login') }}">
@csrf
<div>
<label for="email">Email</label>
<input id="email" type="email" name="email" value="{{ old('email') }}" required autofocus>
@error('email')
<span>{{ $message }}</span>
@enderror
</div>
<div>
<label for="password">Password</label>
<input id="password" type="password" name="password" required autocomplete="current-password">
@error('password')
<span>{{ $message }}</span>
@enderror
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
```
这是一个简单的登录表单,包含邮箱和密码两个输入框,以及提交按钮。注意要添加 CSRF 令牌。
4. 配置路由
在 `routes/web.php` 文件中添加以下路由:
```php
Route::get('login', 'AuthController@showLoginForm')->name('login');
Route::post('login', 'AuthController@login');
```
现在你就可以通过访问 `/login` 路径来进入登录页面了。
以上就是 Laravel 实现账号登录功能的简单步骤,当然还有更多的细节需要注意,比如密码加密、记住我功能等。你可以查看 Laravel 文档来了解更多信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)