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 = [ 'name', 'password','remember_token' ]; protected $hidden = [ 'password','remember_token' ]; }
修改auth.php配置文件
'guards' => [ ... 'admin' => [ 'driver' => 'session', 'provider' => 'admins' ] ], 'providers' => [ ... 'admins' => [ 'driver' => 'eloquent', 'model' => 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 [ 'name' => 'required', 'password' => ['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('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','AdminAuthLoginController@showLoginForm') ->middleware('guest:admin') ->name('admin.login.show'); Route::get('/','AdminHomeController@index') ->name('admin.home'); Route::post('login','AdminAuthLoginController@postLogin') ->middleware('guest:admin') ->name('admin.login.post'); Route::post('logout','AdminAuthLoginController@postLogout') ->middleware('auth:admin') ->name('admin.logout');
把home.blade.php复制到resources/views/admin下
把layouts/app.blade.php复制为layouts/admin.blade.php,修改相应的地方
- @guest(‘admin’)
- admin Login
- {{ Auth::guard(‘admin’)->user()->name }}
@else
@endguest
把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' : '' }}"> <label>E-Mail Address</label> <div> <input> @if ($errors->has('name')) <span> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> </div> <div>has('password') ? ' has-error' : '' }}"> <label>Password</label> <div> <input> @if ($errors->has('password')) <span> <strong>{{ $errors->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'=>'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 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' => AppHttpMiddlewareRedirectIfAdminAuthenticated::class, ... ]; 更改admin路由,将guest:admin改为admin.guest:admin Route::get('login','AdminAuthLoginController@showLoginForm') ->middleware('admin.guest:admin') ->name('admin.login.show'); Route::post('login','AdminAuthLoginController@postLogin') ->middleware('admin.guest:admin') ->name('admin.login.post');