Laravel5.6 實現後臺管理登入(自定義使用者表登入)

listenon發表於2018-07-28

1、新增guard 認證驅動

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
  'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],複製程式碼

2、建立後臺使用者表和model

php artisan make:model Models/Admin -m複製程式碼

3、修改Admin模型類如下

<?php

namespace App\Models;

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',
    ];
}複製程式碼

4、在資料庫遷移檔案 _create_admins_table ,複製 users 遷移檔案裡的欄位

public function up()
{
    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, 新增如下資料:
   $factory->define(App\Models\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), 
            ]; 
  });

開啟命令列輸入:
php artisan tinker 
use App
factory(App\Models\Admin::class,5)->create() 
 //生成5條測試資料,你要幾條就輸入多少(Class,num) 複製程式碼

5、建立控制器

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

6、編輯 Admin/LoginController.php ,程式碼如下:

<?php

namespace App\Http\Controllers\Admin;

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

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

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

    /**
     * 使用者名稱登陸
     */
    public function username()
    {
        return 'name';
    }

    /**
     * 多欄位登入並判斷狀態
     */
    public function attemptLogin(Request $request)
    {
        $username = $request->input('name');
        $password = $request->input('password');

        // 驗證使用者名稱登入方式
        $usernameLogin = $this->guard()->attempt(
            ['name' => $username, 'password' => $password,'status'=>1], $request->has('remember')
        );
        if ($usernameLogin) {
            return true;
        }

        // 驗證手機號登入方式
        $mobileLogin = $this->guard()->attempt(
            ['mobile' => $username, 'password' => $password,'status'=>1], $request->has('remember')
        );
        if ($mobileLogin) {
            return true;
        }

        // 驗證郵箱登入方式
        $emailLogin = $this->guard()->attempt(
            ['email' => $username, 'password' => $password,'status'=>1], $request->has('remember')
        );
        if ($emailLogin) {
            return true;
        }

        return false;
    }

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

    }

    /**
     * 重寫登入檢視頁面
     */

    public function showLoginForm()
    {
        return view('admin.login');
    }

    /**
     * 退出到登入頁面
     */

    public function logout(Request $request)
    {
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect('/admin/login');
    }

    /**
     * 驗證登入
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
            'captcha' => 'required|captcha',
        ]);
    }


    /**
     * 自定義認證驅動
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }
}複製程式碼

7、在 LoginController 中我們在建構函式中修改了 guest 中介軟體

  • app\Http\Middleware\RedirectIfAuthenticated.php
<?php

namespace App\Http\Middleware;

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

class RedirectIfAuthenticated
{
    /**
     * 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)->check()) {
            // 根據不同 guard 跳轉到不同的頁面
            $url = $guard ? '/admin':'/';
            return redirect($url);
        }

        return $next($request);
    }
}複製程式碼

8、編輯 Admin/AdminController.php ,程式碼如下

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth.admin:admin');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        dd('後臺首頁,當前使用者名稱:'.auth('admin')->user()->name);
    }
}複製程式碼

9、在 AdminController 建構函式中我們新增了一個 auth.admin Middlewar

php artisan make:middleware AdminAuth

<?php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @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('admin/login');
            }
        }
        return $next($request);
    }
}複製程式碼

10、在 app\Http\Kernel.php 中註冊:

protected $routeMiddleware = [
    ......
    'auth.admin' => \App\Http\Middleware\AdminAuth::class,
    ......
];複製程式碼

11、在 routes/web.php 中新增如下路由:

Route::group(['prefix'=>'admin','namespace'=>'Admin'],function (){

    //後臺登陸退出
    Route::get('login', 'LoginController@showLoginForm')->name('admin.login');
    Route::post('login', 'LoginController@login');
    Route::post('logout', 'LoginController@logout')->name('admin.logout');

    //後臺首頁
    Route::get('/', 'AdminController@index')->name('admin.index');

});複製程式碼

最後把提交地址的路由改成 {{ route('admin.login') }}


相關文章