您好,登錄后才能下訂單哦!
小編給大家分享一下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 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實現多用戶體系登錄的方法”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。