Laravel 多用户 登录

下面以 Laravel 6.* 为例,其他版本的方法应该类似,自个琢磨去吧

因为 laravel 6.* 去掉了 php artisan make:auth 所以我们先把 laravel/ui 安装下

php artisan migrate
// laravel/ui 2 不支持 laravel6.* ,所以我们要指定版本安装
composer require laravel/ui:^1.0 --dev
// 例子不适用vue或者react, 所以我们只安装bootstrap
php artisan ui bootstrap --auth

npm install && npm run dev

好了,现在最基本的用户登录已经设置好了。接下来我们在增加一个 admin 入口:

  • 创建一个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\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}
  • 修改config/auth.php配置文件
'guards' => [
    ...
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins'
    ]
],

'providers' => [
    ...
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ]
],
  • 创建admin登录后的首页控制器
php artisan make:controller Admin/HomeController

编辑 HomeController:

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('admin.home');
    }
}
  • 创建admin登录控制器
php artisan make:controller Admin\Auth\LoginController

编辑 LoginController:

<?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'));
    }
}
  • 添加 admin 路由文件, 修改 app/providers/RouteServiceProvider.php:
// 添加方法
protected function mapAdminWebRoutes()
{
    Route::middleware('web')
        ->prefix('admin')
        ->namespace($this->namespace)
        ->group(base_path('routes/admin.php'));
}

// 修改方法
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'=>'admin',
        'password'=> bcrypt('123456')
    ]);
}

编辑 DatabaseSeeder.php :

$this->call(AdminsTableSeeder::class);

执行命令

php artisan migrate
php artisan db:seed
  • 解决admin未登录时直接访问 /home 页面不会自动跳转到登录页面的问题: 编辑 app/Exceptions/Handle.php 文件:
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登录时访问登录页面不会自动跳转到 /home页面: 新建并编辑中间件:
    php artisan make:middleware RedirectIfAdminAuthenticated
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAdminAuthenticated
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/admin');
        }

        return $next($request);
    }
}

修改app/Http/Kernel.php:

protected $routeMiddleware = [
    ...
    'admin.guest' => \App\Http\Middleware\RedirectIfAdminAuthenticated::class,
    ...
];

修改路由, 将 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');

ok! 完成~~~ 🌤 ☁ 🌈