Laravel 5 4 實現先後臺登陸

在官網下載 Laravel 5.4 配置並能在訪問php

php artisan make:auth
複製代碼

生成後路由文件 routes/web.php ,自動有html

Auth::routes();

Route::get('/home', 'HomeController@index');
複製代碼

運行web

php artisan migrate
複製代碼

執行命令後會生成 users 表和 password_resets 表,既 用戶表和密碼重置表。能夠測試用戶登陸,註冊,找回密碼功能。 ##自定義用戶表登陸 在 config/auth.php 配置以下:ajax

<?php
return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
           'expire' => 60,
        ],
    ],
];
複製代碼

認證是由 guardsproviders 兩部分構成的, defaults 配置是默認選擇一個 guard 認證驅動,因此咱們在這兩個配置項中分別添加一個 adminadmins 選項。數據庫

<?php
  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
  'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],
複製代碼

建立後臺用戶表和modelapi

php artisan make:model Admin
  php artisan make:migration creaet_admins_table
複製代碼

在數據庫遷移文件 _create_admins_table , 咱們能夠複製 users 遷移文件裏的字段bash

Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
複製代碼

執行php artisan migrate ###生成臨時數據 在 database/factories/ModelFactory.php, 添加以下數據:session

$factory->define(App\Admin::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'password' => $password ?: $password = bcrypt('123456'),
        'email' =>  $faker->email,
        'remember_token' => str_random(10),
    ];
});
複製代碼

打開命令行輸入:app

php artisan tinker
  use App;
  factory(App\Admin::class,5)->create() 
  //生成5條測試數據,你要幾條就輸入多少(Class,num)
複製代碼

###更改 Admin 模型類dom

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
複製代碼

###建立控制器

php artisan make:controller Admin/LoginController
php artisan make:controller Admin/AdminController
複製代碼

編輯 Admin/LoginController.php

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/admin/index';
    protected $username;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
        $this->username = config('admin.global.username');
    }

    /**
     * 重寫登陸視圖頁面
     */
    public function showLogin()
    {
        return view('admin.login.index');
    }

    /**
     * 自定義認證驅動
     * @return mixed
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }


}

複製代碼

修改 app\Http\Middleware\RedirectIfAuthenticated.php:

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            // 根據不一樣 guard 跳轉到不一樣的頁面
            $url = $guard ? 'admin/dash':'/home';
            return redirect($url);
        }

        return $next($request);
    }
複製代碼

編輯 Admin\AdminController.php

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth.admin:admin');
    }
    //
    public function index()
    {
        dd('用戶名:'.auth('admin')->user()->name);
    }
複製代碼
php artisan make:middleware AdminAuthMiddleware
複製代碼

編輯 app\Http\Middleware\AdminAuthMiddleware.php

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('admin/login');
            }
        }
        return $next($request);
    }
複製代碼

app\Http\Kernel.php 中註冊:

protected $routeMiddleware = [
       ··· ···
        'auth.admin' => \App\Http\Middleware\AdminAuthMiddleware::class,
    ];
複製代碼

###註冊路由 編輯 routes/web.php

Route::group(['prefix' => 'admin','namespace' => 'Admin'],function ($router)
{
    $router->get('login', 'LoginController@showLogin')->name('admin.login');
    $router->post('login', 'LoginController@login');
    $router->post('logout', 'LoginController@logout');

    $router->get('index', 'AdminController@index');
});
複製代碼

###視圖文件建立和修改 複製 resources\views\auth\login.blade.php,到 resources\views\admin\login\index.blade.php,修改表單提交地址

{{ url('/login') }} 改爲 {{ route('admin.login') }}
複製代碼

訪問 你的站點/admin/login

###另外知識點:

發現後臺常常是用用戶名登陸的,而不是郵箱。

更改LoginController.php添加:

/**
     * @return string
     */
    public function username()
    {
        return 'name';//登陸名
    }
複製代碼

後修改 resources\views\admin\login\login.blade.php 把郵箱相關的html刪除換成

<div class="form-group">
      <label for="name" class="col-md-4 control-label">Name</label>
      <div class="col-md-6">
        <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}">
      </div>
</div>
複製代碼
相關文章
相關標籤/搜索