zoukankan      html  css  js  c++  java
  • 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', 'AuthAuthController@login');
        Route::get('home/logout', 'AuthAuthController@logout');
        Route::any('home/register', 'AuthAuthController@register');
        
        Route::get('/home', 'HomeController@index');
    });

    这里的Auth文件夹和类文件在 app/Http/Controllers/Auth 目录下:

     

     接着我们打开AuthContrller.php文件,修改或添加自己的类方法,表的字段名按照数据库创建好的来填写,下面是我修改过的,大家也可以参考:

     

    <?php
    
    namespace AppHttpControllersAuth;
    
    use AppUser;
    use IlluminateFoundationAuthAuthenticatesUsers;
    use Validator;
    use AppHttpRequests;
    use Auth;
    use Redirect;
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use IlluminateFoundationAuthThrottlesLogins;
    use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
    
    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 IlluminateFoundationAuthUser 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 AppHttpMiddleware;
    
    use Closure;
    use IlluminateSupportFacadesAuth;
    
    class Authenticate
    {
        /**
         * Handle an incoming request.
         *
         * @param  IlluminateHttpRequest  $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' => AppUser::class,
            ],
            'admins' => [
                'driver' => 'eloquent',
                'model' => AppAdmin::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 IlluminateDatabaseEloquentModel;
    use IlluminateFoundationAuthUser 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', 'AuthAuthController@login');
        Route::get('home/logout', 'AuthAuthController@logout');
        Route::any('home/register', 'AuthAuthController@register');
    
        Route::get('/home', 'HomeController@index');
    
        //后台管理员
        Route::any('admin/login', 'AdminAuthController@login');
        Route::any('admin/logout', 'AdminAuthController@logout');
        Route::any('admin/register', 'AdminAuthController@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 AppHttpControllers;
    
    use IlluminateHttpRequest;
    
    use AppHttpRequests;
    
    class AdminController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('admin');
        }
    
        /**
         * Show the application dashboard.
         *
         * @return IlluminateHttpResponse
         */
        public function index()
        {
            return view('admin.index');
        }
    }

     

    编辑 Admin/AuthController.php 代码如下:

     

    <?php
    
    namespace AppHttpControllersAdmin;
    
    use AppAdmin;
    use IlluminateFoundationAuthAuthenticatesUsers;
    use Validator;
    use AppHttpRequests;
    use Auth;
    use Redirect;
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use IlluminateFoundationAuthThrottlesLogins;
    use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
    
    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 AppHttpMiddleware;
    
    use Closure;
    use IlluminateSupportFacadesAuth;
    
    class AuthAdmin
    {
        /**
         * Handle an incoming request.
         *
         * @param  IlluminateHttpRequest  $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' => AppHttpMiddlewareAuthenticate::class,
            'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
            'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
            'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
            'admin' => AppHttpMiddlewareAuthAdmin::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 ,同样显示注册页面:

     

     

     

     注册并登陆后显示:

    好了,至此我们已经完成前后台用户同时登录认证功能。

  • 相关阅读:
    Mac 上 Go 语言的安装以及编辑器的配置
    【Go学习】立Flag
    python 使用多线程同时执行多个函数
    python闭包
    mfs环境搭建之元数据服务器(master)节点安装-2
    mfs分布式文件系统介绍-01
    vscode中vim插件对ctrl键的设置
    文本截取{}的内容,生成新数组
    如何过滤a数组中b数组存在的值
    js动态加载js文件
  • 原文地址:https://www.cnblogs.com/evai/p/6085437.html
Copyright © 2011-2022 走看看