Laravel 5.2 中多用戶認證實現(前台和后台登錄)


Laravel 5.2中多用戶認證支持,即同時允許不同數據表用戶(如前台用戶、后台用戶、app用戶等)登錄認證。下面我們就來簡單介紹多用戶登錄及注冊功能實現。

1、生成認證腳手架

首先我們使用Laravel 5.2提供的認證腳手架完成初始化工作,打開終端輸入:

php artisan make:auth

 該Artisan命令會生成用戶認證所需的路由、視圖以及HomeController:

 

接着去查看路由文件routes.php,會發現該文件已經被更新:

 

 

其中 Route::auth() 定義了注冊登錄路由, /home 為認證通過后跳轉路由。

這里我重寫了一下登錄驗證的方法:

Route::group(['middleware' => 'web'], function () { //Route::auth(); //前台用戶
    Route::any('home/login', 'Auth\AuthController@login'); Route::get('home/logout', 'Auth\AuthController@logout'); Route::any('home/register', 'Auth\AuthController@register'); Route::get('/home', 'HomeController@index'); });

這里的Auth文件夾和類文件在 app/Http/Controllers/Auth 目錄下:

 

 接着我們打開AuthContrller.php文件,修改或添加自己的類方法,表的字段名按照數據庫創建好的來填寫,下面是我修改過的,大家也可以參考:

 

<?php namespace App\Http\Controllers\Auth; use App\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Validator; use App\Http\Requests; use Auth; use Redirect; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins; /** * Where to redirect users after login / registration. * * @var string */
    protected $redirectTo = '/'; /** * Create a new authentication controller instance. * * @return void */
    public function __construct() { $this->middleware('guest', ['except' => 'logout']); } //登錄頁面
    public function login(Request $request) { if ($request->isMethod('post')) { $validator = $this->validateLogin($request->input()); if ($validator->fails()) { return back()->withErrors($validator)->withInput(); } if (Auth::guard('web')->attempt($this->validateUser($request->input()))) { $request->session()->put('email', $request->email); return Redirect::to('home')->with('success', '登錄成功!'); }else { return back()->with('error', '賬號或密碼錯誤')->withInput(); } } return view('auth.login'); } //登錄頁面驗證
    protected function validateLogin(array $data) { return Validator::make($data, [ 'email' => 'required',
            'password' => 'required', ], [ 'required' => ':attribute 為必填項',
            'min' => ':attribute 長度不符合要求' ], [ 'email' => '郵箱',
            'password' => '密碼' ]); } //驗證用戶字段
    protected function validateUser(array $data) { return [ 'email' => $data['email'],
            'password' => $data['password'] ]; } //退出登錄
    public function logout() { if(Auth::guard('web')->user()){ Auth::guard('web')->logout(); } return Redirect::to('home'); } //注冊
    public function register(Request $request) { if ($request->isMethod('post')) { $validator = $this->validateRegister($request->input()); if ($validator->fails()) { return back()->withErrors($validator)->withInput(); } $user = new User(); $user->name = $request->name;$user->email = $request->email; $user->password = bcrypt($request->password); $user->create_time = time(); $user->update_time = time(); if($user->save()){ return redirect('home/login')->with('success', '注冊成功!'); }else{ return back()->with('error', '注冊失敗!')->withInput(); } } return view('auth.register'); } protected function validateRegister(array $data) { return Validator::make($data, [ 'name' => 'required|alpha_num|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'password_confirmation' => 'required|min:6|' ], [ 'required' => ':attribute 為必填項',
            'min' => ':attribute 長度不符合要求',
            'confirmed' => '兩次輸入的密碼不一致',
            'unique' => '該郵箱已經被人占用',
            'alpha_num' => ':attribute 必須為字母或數字' ], [ 'name' => '昵稱',
            'email' => '郵箱',
            'password' => '密碼',
            'password_confirmation' => '確認密碼' ]); } }

然后修改app目錄下的 User.php:

<?php namespace App; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { /** * The attributes that are mass assignable. * * @var array */
    protected $table = 'users'; //指定主鍵
    protected $primaryKey = 'userid'; //指定允許批量賦值的字段
    protected $fillable = [ 'name', 'email', 'password', ]; //指定不允許批量賦值的字段
     protected $guarded = []; //自動維護時間戳
    public $timestamps = false; //定制時間戳格式
    protected $dateFormat = 'U'; /** * 避免轉換時間戳為時間字符串 */
    public function fromDateTime($value) { return $value; } //將默認增加時間轉化為時間戳
    protected function getDateFormat() { return time(); } /** * The attributes excluded from the model's JSON form. * * @var array */
    protected $hidden = [ 'password', 'remember_token', 'app_token','email' ]; }

 

再去 resource/view/auth 目錄下把login.balde.php 和register.blade.php 的form表單 action 分別改為  action="{{ url('home/login') }}" 和 action="{{ url('home/register') }}", 和layouts/app.blade.php 改為:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700" rel='stylesheet' type='text/css'>

    <!-- Styles -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}} <style> body { font-family: 'Lato';
        } .fa-btn { margin-right: 6px;
        }
    </style>
</head>
<body id="app-layout">
    <nav class="navbar navbar-default">
        <div class="container">
            <div class="navbar-header">

                <!-- Collapsed Hamburger -->
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                    <span class="sr-only">Toggle Navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <!-- Branding Image -->
                <a class="navbar-brand" href="{{ url('/') }}"> Laravel </a>
            </div>

            <div class="collapse navbar-collapse" id="app-navbar-collapse">
                <!-- Left Side Of Navbar -->
                <ul class="nav navbar-nav">
                    <li><a href="{{ url('/home') }}">Home</a></li>
                </ul>

                <!-- Right Side Of Navbar -->
                <ul class="nav navbar-nav navbar-right">
                    <!-- Authentication Links --> @if (Auth::guest()) <li><a href="{{ url('home/login') }}">Login</a></li>
                        <li><a href="{{ url('home/register') }}">Register</a></li> @else <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {{ Auth::user()->name }} <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu" role="menu">
                                <li><a href="{{ url('home/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>
                            </ul>
                        </li> @endif </ul>
            </div>
        </div>
    </nav> @yield('content') <!-- JavaScripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> {{-- <script src="{{ elixir('js/app.js') }}"></script> --}} </body>
</html>

 

還有修改 app/Http/Middleware/Authenticate.php 文件:

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */
    public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } else { return redirect()->guest('home/login'); } } return $next($request); } }

 

2、實現前台用戶登錄

接下來我們先實現前台用戶登錄,也就是Laravel自帶的User用戶登錄。通過上面的腳手架,我們已經生成了認證所需的所有代碼,剩下要做的就是使用遷移命令創建用戶認證相關表:

 

php artisan migrate

 

該命令執行后生成 users 表和 password_resets 表,分別為用戶主表和密碼重置表。

然后我們就可以在瀏覽器中輸入 http://localhost/home 訪問頁面,發現頁面自動跳轉到了登錄頁面,這里的原理就是 app/Http/Middleware/Authenticate.php 文件,現在我們是登錄不上去了,所以我們先點擊右上角的register注冊一個用戶:

 

 

成功登陸后就可以看到效果了:

這是前台用戶登錄的效果,然后看后台登錄的實現。

3、編輯認證配置文件

要實現多用戶認證,首先要配置認證配置文件,在 config 目錄下的auth.php,配置如下:

<?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */

    'defaults' => [ 'guard' => 'web',
        'passwords' => 'users', ],

    /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */

    'guards' => [ 'web' => [ 'driver' => 'session',
            'provider' => 'users', ],

        'api' => [ 'driver' => 'token',
            'provider' => 'users', ],
        'admin' => [ 'driver' => 'session',
            'provider' => 'admins', ], ],

    /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */

    'providers' => [ 'users' => [ 'driver' => 'eloquent',
            'model' => App\User::class, ],
        'admins' => [ 'driver' => 'eloquent',
            'model' => App\Admin::class, ],

        // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ],
    ],

    /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | Here you may set the options for resetting passwords including the view | that is your password reset e-mail. You may also set the name of the | table that maintains all of the reset tokens for your application. | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */

    'passwords' => [ 'users' => [ 'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60, ], ], ];

認證是由 guard 和 provider 兩部分構成的(參考用戶認證文檔),所以我們在這兩個配置項中分別新增了 admin 和 admins 選項。

4、創建后台用戶模型

接下來我們來實現后台用戶登錄,首先使用如下Artisan命令生成后台用戶模型:

 

php artisan make:model Admin --migration

帶上 --migration 選項會生成對應用戶表 admins ,我們定義該數據表字段和 users 一樣,生成的文件在database/migration目錄下:

 

 

Schema::create('admins', function (Blueprint $table) { $table->increments('adminid'); $table->string('name'); $table->string('account_number', 128); $table->string('password', 64); $table->rememberToken(); $table->integer('create_time'); $table->integer('update_time'); });

 

然后通過運行遷移命令生成該表:

 

php artisan migrate

 

然后更新 Admin 模型類如下:

 

<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { //表名
    protected $table = 'admins'; //指定主鍵
    protected $primaryKey = 'adminid'; //指定允許批量賦值的字段
    protected $fillable = [ 'name', 'account_number', 'password', ]; //指定不允許批量賦值的字段 // protected $guarded = []; //自動維護時間戳
    public $timestamps = false; //定制時間戳格式
    protected $dateFormat = 'U'; //將默認增加時間轉化為時間戳
    protected function getDateFormat() { return time(); } /** * The attributes excluded from the model's JSON form. * * @var array */
    protected $hidden = [ 'password', 'remember_token' ]; }

 

5、定義后台用戶認證路由及控制器

接下來我們來定義后台用戶認證路由,修改 routes.php 代碼如下:

 

Route::group(['middleware' => 'web'], function () { //Route::auth(); //前台用戶
    Route::any('home/login', 'Auth\AuthController@login'); Route::get('home/logout', 'Auth\AuthController@logout'); Route::any('home/register', 'Auth\AuthController@register'); Route::get('/home', 'HomeController@index'); //后台管理員
    Route::any('admin/login', 'Admin\AuthController@login'); Route::any('admin/logout', 'Admin\AuthController@logout'); Route::any('admin/register', 'Admin\AuthController@register'); Route::get('/admin', 'AdminController@index'); });

然后使用Artisan命令創建對應控制器:

php artisan make:controller Admin/AuthController php artisan make:controller AdminController
php artisan make:middleware AuthAdmin

 

app/Http 目錄下會多出Admin認證的文件夾和AdminController.php文件,修改AdminController.php:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class AdminController extends Controller { /** * Create a new controller instance. * * @return void */
    public function __construct() { $this->middleware('admin'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */
    public function index() { return view('admin.index'); } }

 

編輯 Admin/AuthController.php 代碼如下:

 

<?php namespace App\Http\Controllers\Admin; use App\Admin; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Validator; use App\Http\Requests; use Auth; use Redirect; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { use AuthenticatesAndRegistersUsers, ThrottlesLogins; // protected $redirectTo = 'admin'; // protected $guard = 'admin'; // protected $loginView = 'admin.login'; // protected $registerView = 'admin.register';

    public function __construct() { $this->middleware('guest:admin', ['except' => 'logout']); } //登錄
    public function login(Request $request) { if ($request->isMethod('post')) { $validator = $this->validateLogin($request->input()); if ($validator->fails()) { return back()->withErrors($validator)->withInput(); } if (Auth::guard('admin')->attempt(['account_number'=>$request->account_number, 'password'=>$request->password])) { return Redirect::to('admin')->with('success', '登錄成功!');     //login success, redirect to admin
            } else { return back()->with('error', '賬號或密碼錯誤')->withInput(); } } return view('admin.login'); } //登錄頁面驗證
    protected function validateLogin(array $data) { return Validator::make($data, [ 'account_number' => 'required|alpha_num',
            'password' => 'required', ], [ 'required' => ':attribute 為必填項',
            'min' => ':attribute 長度不符合要求' ], [ 'account_number' => '賬號',
            'password' => '密碼' ]); } //退出登錄
    public function logout() { if(Auth::guard('admin')->user()){ Auth::guard('admin')->logout(); } return Redirect::to('admin/login'); } //注冊
    public function register(Request $request) { if ($request->isMethod('post')) { $validator = $this->validateRegister($request->input()); if ($validator->fails()) { return back()->withErrors($validator)->withInput(); } $user = new Admin(); $user->name = $request->name; $user->account_number = $request->account_number; $user->password = bcrypt($request->password); $user->create_time = time(); $user->update_time = time(); if($user->save()){ return redirect('admin/login')->with('success', '注冊成功!'); }else{ return back()->with('error', '注冊失敗!')->withInput(); } } return view('admin.register'); } protected function validateRegister(array $data) { return Validator::make($data, [ 'name' => 'required|alpha_num|max:255',
            'account_number' => 'required|alpha_num|unique:admins',
            'password' => 'required|min:6|confirmed',
            'password_confirmation' => 'required|min:6|' ], [ 'required' => ':attribute 為必填項',
            'min' => ':attribute 長度不符合要求',
            'confirmed' => '兩次輸入的密碼不一致',
            'unique' => '該賬戶已存在',
            'alpha_num' => ':attribute 必須為字母或數字',
            'max' => ':attribute 長度過長' ], [ 'name' => '昵稱',
            'account_number' => '賬號',
            'password' => '密碼',
            'password_confirmation' => '確認密碼' ]); } }

 

編輯 Middleware/AuthAdmin.php 代碼如下:

 

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class AuthAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */
    public function handle($request, Closure $next, $guard = null) { if (Auth::guard('admin')->guest()) { if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } else { return redirect()->guest('admin/login'); } } return $next($request); } }

 

最后再修改Http/Kernel.php,最下方添加一個 admin 認證用戶指向:

 

protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\AuthAdmin::class, ];

 

6、視圖文件創建及修改

最后我們要創建后台用戶認證對應視圖文件,這里我們簡單拷貝前台用戶視圖模板並稍作修改即可:

 

cp -r resources/views/auth resources/views/admin

 

修改 resources/views/admin 目錄下登錄及注冊表單提交地址:

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">Login</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('admin/login') }}">
                        {!! csrf_field() !!}

                        <div class="form-group{{ $errors->has('account_number') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Account Number</label>

                            <div class="col-md-6">
                                <input type="text" class="form-control" name="account_number" value="{{ old('account_number') }}">

                                @if ($errors->has('account_number'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('account_number') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password">

                                @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-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember"> Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-btn fa-sign-in"></i>Login
                                </button>

                                <a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

 

register.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">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('admin/register') }}">
                        {!! csrf_field() !!}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" value="{{ old('name') }}">

                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('account_number') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Acoount Number</label>

                            <div class="col-md-6">
                                <input type="text" class="form-control" name="account_number" value="{{ old('account_number') }}">

                                @if ($errors->has('account_number'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('account_number') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password">

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Confirm Password</label>

                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password_confirmation">

                                @if ($errors->has('password_confirmation'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-btn fa-user"></i>Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

 

再把 home.blade.php 復制到admin下,重名為index.php,app.blade.php 復制一個並重命名為admin.ablde.php:

 

cp /resources/views/home.blade.php /resources/views/index.blade.php
cp /resources/views/layouts/app.blade.php /resources/views/layouts/admin.blade.php

 

admin.blade.php 修改如下:

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700" rel='stylesheet' type='text/css'>

    <!-- Styles -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}}

    <style>
        body {
            font-family: 'Lato';
        }

        .fa-btn {
            margin-right: 6px;
        }
    </style>
</head>
<body id="app-layout">
    <nav class="navbar navbar-default">
        <div class="container">
            <div class="navbar-header">

                <!-- Collapsed Hamburger -->
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                    <span class="sr-only">Toggle Navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <!-- Branding Image -->
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravel
                </a>
            </div>

            <div class="collapse navbar-collapse" id="app-navbar-collapse">
                <!-- Left Side Of Navbar -->
                <ul class="nav navbar-nav">
                    <li><a href="{{ url('/admin') }}">Home</a></li>
                </ul>

                <!-- Right Side Of Navbar -->
                <ul class="nav navbar-nav navbar-right">
                    <!-- Authentication Links -->
                    @if (!Auth::guest('admin')->user())
                        <li><a href="{{ url('admin/login') }}">Login</a></li>
                        <li><a href="{{ url('admin/register') }}">Register</a></li>
                    @else
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                {{ Auth::guard('admin')->user()->name }} <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu" role="menu">
                                <li><a href="{{ url('admin/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>
                            </ul>
                        </li>
                    @endif
                </ul>
            </div>
        </div>
    </nav>

    @yield('content')

    <!-- JavaScripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    {{-- <script src="{{ elixir('js/app.js') }}"></script> --}}
</body>
</html>

 

 

7、實現后台用戶認證

在瀏覽器中訪問 http://localhost/admin/register ,同樣顯示注冊頁面:

 

 

 

 注冊並登陸后顯示:

好了,至此我們已經完成前后台用戶同時登錄認證功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM