laravel框架用户名登录
时间: 2023-09-03 07:11:08 浏览: 154
Laravel实现用户注册和登录
在 Laravel 框架中,可以使用 Laravel 自带的身份验证系统来实现用户名登录。具体步骤如下:
1. 配置数据库
在 `.env` 文件中配置数据库连接信息,如下所示:
```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
```
2. 创建用户表
运行以下 Artisan 命令来创建用户表:
```
php artisan make:model User -m
```
该命令将同时生成 `app/User.php` 模型文件和 `database/migrations/xxxx_xx_xx_xxxxxx_create_users_table.php` 迁移文件。在迁移文件中定义用户表的字段和属性,如下所示:
```php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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
```
3. 创建控制器
运行以下 Artisan 命令来创建控制器:
```
php artisan make:controller AuthController
```
在 `AuthController` 中定义登录和退出登录方法,如下所示:
```php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('/dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
```
4. 创建路由
在 `routes/web.php` 文件中定义登录和退出登录路由,如下所示:
```php
Route::get('login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout'])->name('logout');
```
5. 创建登录表单
在 `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>
```
以上就是使用 Laravel 框架实现用户名登录的步骤,希望能对你有所帮助!
阅读全文