laravel如何实现多用户体系登录

laraveli添加一个或多个用户表,以admin为例。

部分文件内容可能需要根据实际情况修改

推荐:laravel教程

创建一个Admin模型

php artisan make:model Admin -m

编写admins表字段

Schema::create('admins', function (Blueprint $table) {     $table->increments('id');     $table->string('name')->unique();     $table->string('password');     $table->rememberToken();     $table->timestamps(); });

编辑admin模型

<?php namespace App; use IlluminateNotificationsNotifiable; use IlluminateFoundationAuthUser as Authenticatable; /**  * @property int $id  * @property CarbonCarbon $created_at  * @property CarbonCarbon $updated_at  */ class Admin extends Authenticatable {     use Notifiable;     protected $fillable = [         &#39;name&#39;, &#39;password&#39;,&#39;remember_token&#39;     ];     protected $hidden = [         &#39;password&#39;,&#39;remember_token&#39;     ]; }

修改auth.php配置文件

'guards' =&gt; [     ...     'admin' =&gt; [         'driver' =&gt; 'session',         'provider' =&gt; 'admins'     ] ], 'providers' =&gt; [     ...     'admins' =&gt; [         'driver' =&gt; 'eloquent',         'model' =&gt; AppAdmin::class,     ] ],

在app/http/Controllers下创建目录Admin/Auth

在Admin目录下创建文件HomeController.php(这个文件用来测试登录成功后的跳转页面)

<?php namespace AppHttpControllersAdmin; use AppHttpControllersController; use IlluminateHttpRequest; class HomeController extends Controller {     /**      * HomeController constructor.      */     public function __construct()     {         $this->middleware('auth:admin');     }     /**      * Show the application dashboard.      *      * @return IlluminateHttpResponse      */     public function index()     {         return view('admin.home');     } }

使用命令生成一个Request

php artisan make:request AdminLoginRequest

此时在app/Http/Request目录下便生成了这个文件,然后编辑这个文件

<?php namespace AppHttpRequests; use IlluminateFoundationHttpFormRequest; class AdminLoginRequest extends FormRequest {     /**      * 确定用户是否有权发出此请求.      *      * @return bool      */     public function authorize()     {         return true;     }     /**      * 获取适用于请求的验证规则.      *      * @return array      */     public function rules()     {         return [             &#39;name&#39;     => 'required',             'password' =&gt; ['required', 'min:6'] //密码必须,最小长度为6         ];     } }

在Admin/Auth目录下创建文件LoginController.php

<?php namespace AppHttpControllersAdminAuth; use AppHttpControllersController; use AppHttpRequestsAdminLoginRequest; use IlluminateSupportFacadesAuth; class LoginController extends Controller {     public function showLoginForm()     {         return view(&#39;admin.auth.login&#39;);     }     public function postLogin(AdminLoginRequest $loginRequest)     {         $data = $loginRequest->only('name', 'password');         $result = Auth::guard('admin')-&gt;attempt($data, true);         if ($result) {             return redirect(route('admin.home'));         } else {             return redirect()-&gt;back()                 -&gt;with('name', $loginRequest-&gt;get('name'))                 -&gt;withErrors(['name' =&gt; '用户名或密码错误']);         }     }     public function postLogout()     {         Auth::guard('admin')-&gt;logout();         return redirect(route('admin.login.show'));     } }

添加路由。打开app/providers/RouteServiceProvider.php

在方法mapWebRoutes()方法后面增加一个方法

protected function mapAdminWebRoutes()     {         Route::middleware('web')             -&gt;prefix('admin')             -&gt;namespace($this-&gt;namespace)             -&gt;group(base_path('routes/admin.php'));     }

在map()方法里调用上面增加的方法

public function map()     {         $this-&gt;mapApiRoutes();         $this-&gt;mapAdminWebRoutes();//调用新增的方法         $this-&gt;mapWebRoutes();     }

在routes目录下增加一个路由文件admin.php

<?php Route::get(&#39;login&#39;,&#39;AdminAuthLoginController@showLoginForm&#39;)     ->middleware('guest:admin')     -&gt;name('admin.login.show'); Route::get('/','AdminHomeController@index')     -&gt;name('admin.home'); Route::post('login','AdminAuthLoginController@postLogin')     -&gt;middleware('guest:admin')     -&gt;name('admin.login.post'); Route::post('logout','AdminAuthLoginController@postLogout')     -&gt;middleware('auth:admin')     -&gt;name('admin.logout');

把home.blade.php复制到resources/views/admin下

把layouts/app.blade.php复制为layouts/admin.blade.php,修改相应的地方


把login.blade.php复制到admin/Auth目录下

@extends('layouts.admin') @section('content')     <div>         <div>             <div>                 <div>                     <div>Admin Login</div>                     <div>                         <form>                             {{ csrf_field() }}                             <div>has('name') ? ' has-error' : '' }}"&gt;                                 <label>E-Mail Address</label>                                 <div>                                     <input>                                     @if ($errors-&gt;has('name'))                                         <span>                                         <strong>{{ $errors-&gt;first('name') }}</strong>                                     </span>                                     @endif                                 </div>                             </div>                             <div>has('password') ? ' has-error' : '' }}"&gt;                                 <label>Password</label>                                 <div>                                     <input>                                     @if ($errors-&gt;has('password'))                                         <span>                                         <strong>{{ $errors-&gt;first('password') }}</strong>                                     </span>                                     @endif                                 </div>                             </div>                             <div>                                 <div>                                     <button>                                         Login                                     </button>                                 </div>                             </div>                         </form>                     </div>                 </div>             </div>         </div>     </div> @endsection

数据填充

php artisan make:seed AdminsTableSeeder

编辑AdminsTableSeeder.php

public function run()     {         AppAdmin::insert([             'name'=&gt;'yzha5',             'password'=&gt; bcrypt('123456')         ]);     } DatabaseSeeder.php $this-&gt;call(AdminsTableSeeder::class);

文件上传至服务器,登入服务器,执行填充命令

php artisan migrate php artisan db:seed

此时,直接打开http://xxx/admin并不会跳转到http://xxx/admin/login,因此需要处理一些异常。打开app/Exceptions/Handle.php

重写unauthenticated()方法。

use IlluminateSupportFacadesRoute; protected function unauthenticated($request, AuthenticationException $exception)     {         return starts_with(Route::currentRouteName(), 'admin')             ? redirect(route('admin.login.show'))             : parent::unauthenticated($request, $exception);     }

完善一下

以上代码,当admin登录后,再次访问/admin/login这个URI时,会自动跳转到/home这个URI,这是因为guest这个中间件默认跳转到了/home,也就是middleware目录下的RedirectIfAuthenticated.php这个文件。

解决方法为:

创建一个中单件,名为:RedirectIfAdminAuthenticated

php artisan make:middleware RedirectIfAdminAuthenticated

编辑这个文件:

<?php namespace AppHttpMiddleware; use Closure; use IlluminateSupportFacadesAuth; class RedirectIfAdminAuthenticated {     /**      * Handle an incoming request.      *      * @param $request      * @param Closure $next      * @param null $guard      * @return IlluminateHttpRedirectResponse|IlluminateRoutingRedirector|mixed      */     public function handle($request, Closure $next, $guard = null)     {         if (Auth::guard($guard)->check()) {             return redirect('/admin');         }         return $next($request);     } } 在Kernel.php中添加一行 protected $routeMiddleware = [         ...         'admin.guest' =&gt; AppHttpMiddlewareRedirectIfAdminAuthenticated::class,         ...     ]; 更改admin路由,将guest:admin改为admin.guest:admin Route::get('login','AdminAuthLoginController@showLoginForm')     -&gt;middleware('admin.guest:admin')     -&gt;name('admin.login.show'); Route::post('login','AdminAuthLoginController@postLogin')     -&gt;middleware('admin.guest:admin')     -&gt;name('admin.login.post');

以上就是

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享