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 Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; /** * @property int $id * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at */ class Admin extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'password','remember_token' ]; protected $hidden = [ 'password','remember_token' ]; }
修改auth.php配置文件
'guards' => [ ... 'admin' => [ 'driver' => 'session', 'provider' => 'admins' ] ], 'providers' => [ ... 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ] ],
在app/Http/Controllers下创建目录Admin/Auth
在Admin目录下创建文件HomeController.php(这个文件用来测试登录成功后的跳转页面)
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class HomeController extends Controller { /** * HomeController constructor. */ public function __construct() { $this->middleware('auth:admin'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('admin.home'); } }
使用命令生成一个Request
php artisan make:request AdminLoginRequest
此时在app/Http/Request目录下便生成了这个文件,然后编辑这个文件
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class AdminLoginRequest extends FormRequest { /** * 确定用户是否有权发出此请求. * * @return bool */ public function authorize() { return true; } /** * 获取适用于请求的验证规则. * * @return array */ public function rules() { return [ 'name' => 'required', 'password' => ['required', 'min:6'] //密码必须,最小长度为6 ]; } }
在Admin/Auth目录下创建文件LoginController.php
<?php namespace App\Http\Controllers\Admin\Auth; use App\Http\Controllers\Controller; use App\Http\Requests\AdminLoginRequest; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { public function showLoginForm() { return view('admin.auth.login'); } public function postLogin(AdminLoginRequest $loginRequest) { $data = $loginRequest->only('name', 'password'); $result = Auth::guard('admin')->attempt($data, true); if ($result) { return redirect(route('admin.home')); } else { return redirect()->back() ->with('name', $loginRequest->get('name')) ->withErrors(['name' => '用户名或密码错误']); } } public function postLogout() { Auth::guard('admin')->logout(); return redirect(route('admin.login.show')); } }
添加路由。打开app/providers/RouteServiceProvider.php
在方法mapWebRoutes()方法后面增加一个方法
protected function mapAdminWebRoutes() { Route::middleware('web') ->prefix('admin') ->namespace($this->namespace) ->group(base_path('routes/admin.php')); }
在map()方法里调用上面增加的方法
public function map() { $this->mapApiRoutes(); $this->mapAdminWebRoutes();//调用新增的方法 $this->mapWebRoutes(); }
在routes目录下增加一个路由文件admin.php
<?php Route::get('login','Admin\Auth\LoginController@showLoginForm') ->middleware('guest:admin') ->name('admin.login.show'); Route::get('/','Admin\HomeController@index') ->name('admin.home'); Route::post('login','Admin\Auth\LoginController@postLogin') ->middleware('guest:admin') ->name('admin.login.post'); Route::post('logout','Admin\Auth\LoginController@postLogout') ->middleware('auth:admin') ->name('admin.logout');
把home.blade.php复制到resources/views/admin下
把layouts/app.blade.php复制为layouts/admin.blade.php,修改相应的地方
<ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @guest('admin') <li><a href="{{ route('admin.login.show') }}">admin Login</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"> {{ Auth::guard('admin')->user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <a href="{{ route('admin.logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('admin.logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endguest </ul>
把login.blade.php复制到admin/Auth目录下
@extends('layouts.admin') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Admin Login</div> <div class="panel-body"> <form class="form-horizontal" method="POST" action="{{ route('admin.login.post') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}"> <label for="name" class="col-md-4 control-label">E-Mail Address</label> <div class="col-md-6"> <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus> @if ($errors->has('name')) <span class="help-block"> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}"> <label for="password" class="col-md-4 control-label">Password</label> <div class="col-md-6"> <input id="password" type="password" class="form-control" name="password" required> @if ($errors->has('password')) <span class="help-block"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-8 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Login </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
数据填充
php artisan make:seed AdminsTableSeeder
编辑AdminsTableSeeder.php
public function run() { \App\Admin::insert([ 'name'=>'yzha5', 'password'=> bcrypt('123456') ]); } DatabaseSeeder.php $this->call(AdminsTableSeeder::class);
文件上传至服务器,登入服务器,执行填充命令
php artisan migrate php artisan db:seed
此时,直接打开http://xxx/admin并不会跳转到http://xxx/admin/login,因此需要处理一些异常。打开app/Exceptions/Handle.php
重写unauthenticated()方法。
use Illuminate\Support\Facades\Route; 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 App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class RedirectIfAdminAuthenticated { /** * Handle an incoming request. * * @param $request * @param Closure $next * @param null $guard * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|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' => \App\Http\Middleware\RedirectIfAdminAuthenticated::class, ... ]; 更改admin路由,将guest:admin改为admin.guest:admin Route::get('login','Admin\Auth\LoginController@showLoginForm') ->middleware('admin.guest:admin') ->name('admin.login.show'); Route::post('login','Admin\Auth\LoginController@postLogin') ->middleware('admin.guest:admin') ->name('admin.login.post');
以上是laravel如何实现多用户体系登录的详细内容。更多信息请关注PHP中文网其他相关文章!

在Laravel全栈开发中,管理API和前端逻辑的有效方法包括:1)使用RESTful控制器和资源路由管理API;2)通过Blade模板和Vue.js或React处理前端逻辑;3)通过API版本控制和分页优化性能;4)保持后端和前端逻辑分离,确保可维护性和可扩展性。

TotackleculturalIntricaciesIndistributedTeams,fosteranenvironmentcelebratingDifferences,BemindfulofCommunication,andusetoolsforclarity.1)enmulcultulalexchangessessionStossessessionStosharestories andraditions.2)

Toassesstheeffectivenessofremotecommunication,focuson:1)Engagementmetricslikemessagefrequencyandresponsetime,2)Sentimentanalysistogaugeemotionaltone,3)Meetingeffectivenessthroughattendanceandactionitems,and4)Networkanalysistounderstandcommunicationpa

toprotectSentiveDatainDistributedTeams,实现amulti-faceTedEblect:1)使用EndEnd-to-endencryptignterforsecurocommunication,2)基于applyrole的acccessControl(rbac)tomanagepermissions,3)

不,emailisnotthebostforremotecollaborationtoday.modern PlatformLack,Microsoft Teams,Zoom,Asana和Trellofferreal时间通信,项目管理,项目管理和IntintegrationFeatureSthanCteAncteAncteAmworkworkesseffiquice。

协作文档编辑是分布式团队优化工作流程的有效工具。它通过实时协作和反馈循环提升沟通和项目进度,常用工具包括GoogleDocs、MicrosoftTeams和Notion。使用时需注意版本控制和学习曲线等挑战。

ThepreviousversionofLaravelissupportedwithbugfixesforsixmonthsandsecurityfixesforoneyearafteranewmajorversion'srelease.Understandingthissupporttimelineiscrucialforplanningupgrades,ensuringprojectstability,andleveragingnewfeaturesandsecurityenhancemen

Laravelcanbeeffectivelyusedforbothfrontendandbackenddevelopment.1)Backend:UtilizeLaravel'sEloquentORMforsimplifieddatabaseinteractions.2)Frontend:LeverageBladetemplatesforcleanHTMLandintegrateVue.jsfordynamicSPAs,ensuringseamlessfrontend-backendinteg


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1
好用且免费的代码编辑器