Laravel —— 多套用户登录

Laravel 自带了用户认证 Auth。有看守器和提供器来实现。

对于前后台都需要登录的系统,需要添加一套用户认证。

本文中使用 Laravel 9。

 

一、生成自带的用户认证

1
php artisan ui:auth

1、执行脚手架命令后生成下面的代码

  - app/Http/Controllers/Auth/   相关控制器

  - resources/views/auth/    相关页面

  - routes/web.php     路由中追加了 Auth 系列

2、对应用户表 users,

3、加上 config/auth.php 配置文件中设置的 guards、providers,即可实现登录注册、邮箱验证、修改密码等操作。

 

二、生成新用户表 members

  创建 migration,生成自定义表

 

三、修改配置文件

1、在 config/auth.php 文件中,providers 数组中添加,

1
2
3
4
'members' => [
    'driver' => 'eloquent',
    'model' => App\Models\Member::class,
],

 

2、guards 数组中添加

1
2
3
4
'front' => [
    'driver' => 'session',
    'provider' => 'members',
],

 

四、重写登录注册方法

底层文件再 vendor/laravel/ui/auth-backend/ 目录,

继承相应的控制器,并根据需求重写方法。

1、重写登录控制器方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 修改成上面自定义的看守器
    protected function guard()
    {
        return Auth::guard(‘front’);
    }
 
// 修改登录表单用户名
    public function username()
    {
        return 'account';
    }
 
// 修改实现多类型账号登录
    protected function attemptLogin(Request $request)
    {
        return collect(['mail', 'tel', 'name'])->contains(function ($value) use ($request) {
            $account = $request->get($this->username());
            $password = $request->get('password');
 
            return $this->guard()->attempt(
                [$value => $account, 'password' => $password], $request->filled('remember')
            );
        });
    }

2、其他控制器,按照需求重写即可。

 

五、给路由添加登录验证

 

1、新建中间件文件 

1
php artisan make:middleware AuthMember// 修改文件中的 handle 方法
    public function handle(Request $request, Closure $next)
    {
        if (\Auth::guard('front')->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        return $next($request);
    }

 

2、把新建的路由,添加在 app/Http/Kernel.php 文件中

1
2
3
4
5
6
7
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    ...
    ...
     
    'auth.member' => \App\Http\Middleware\AuthMember::class,
];

 

3、路由中添加中间件

1
2
3
Route::prefix('/')->middleware('auth.member')->group(function(){
    Route::get('/', [IndexController::class, 'index'])->name('home');
});

 

posted @   菜乌  阅读(749)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示