laraveli관리자를 예로 들어 하나 이상의 사용자 테이블을 추가합니다.
실제 상황에 따라 일부 파일 내용을 수정해야 할 수도 있습니다
권장: laravel tutorial
Create 관리 모델# 🎜🎜#
php artisan make:model Admin -m
Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
<?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' ]; }
'guards' => [ ... 'admin' => [ 'driver' => 'session', 'provider' => 'admins' ] ], 'providers' => [ ... 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ] ],
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'); } }
php artisan make:request AdminLoginRequest
<?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 ]; } }
<?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(); }
경로 디렉터리에 라우팅 파일 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에 복사
레이아웃 넣기/앱 복사. 블레이드.php를 레이아웃/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를 관리자/인증 디렉토리에 복사
@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
public function run() { \App\Admin::insert([ 'name'=>'yzha5', 'password'=> bcrypt('123456') ]); } DatabaseSeeder.php $this->call(AdminsTableSeeder::class);
php artisan migrate php artisan db:seed
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); }
해결책은 다음과 같습니다.
이름이 RedirectIfAdminAuthenticatedphp 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!