A-A+

laravel利用auth完成后台的登录模块

2020年01月07日 Laravel, php 暂无评论 阅读 785 views 次

开发环境:windows10、iis、php7.3,安装好laravel

 

1、创建管理员admin数据表

(1)命令提示符执行:php artisan make:migration create_admin_table

(2)修改database/migration/*_create_admin_table.php中的up()方法,如下:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    //php artisan make:migration create_users_table
    //php artisan migrate
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->integer('mobile')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
}

 

(3)终端执行 php artisan migrate 这时候,数据库会自动添加表admin。

(4)修改一下表中字段的字段长度,例如varchar(255).

当然,手动建表也可以。

 

2、生产数据表模型

php artisan make:model Models/Admin,会自动创建Models/Admin.php这个模型文件,修改为:

<?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',
    ];
}

 

3、添加后台后台路由

Route::prefix('admin')->namespace('Admin')->group(function () {
    //后台首页
    $this->get('login', 'LoginController@showLoginForm')->name('admin.login');
    $this->post('login', 'LoginController@login');
    $this->post('logout', 'LoginController@logout')->name('admin.logout');
});

 

4、新建管理员登录控制器

php artisan make:controller Admin/LoginController

并添加代码如下(参考auth/LoginController):

<?php

namespace App\Http\Controllers\Admin;

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

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.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

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

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

    protected function guard()
    {
        return auth()->guard('admin');
    }

    /**
     * 后台管理员退出跳转到后台登录页面
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/admin/login');
    }
    protected function attemptLogin(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        // 验证用户名登录方式
        $usernameLogin = $this->guard()->attempt(
            ['name' => $username, 'password' => $password], $request->has('remember')
        );
        if ($usernameLogin) {
            return true;
        }
        // 验证手机号登录方式
        $mobileLogin = $this->guard()->attempt(
            ['mobile' => $username, 'password' => $password], $request->has('remember')
        );
        if ($mobileLogin) {
            return true;
        }

        // 验证邮箱登录方式
        $emailLogin = $this->guard()->attempt(
            ['email' => $username, 'password' => $password], $request->has('remember')
        );
        if ($emailLogin) {
            return true;
        }
        return false;
    }

    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    public function username()
    {
        return 'username';
    }
}

 

 

5、添加管理员认证,修改config/auth.php文件:

'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,
    ]

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

 

 

6、创建admin登录所用的中间件

php artisan make:middleware AdminAuthMiddleware

添加代码如下:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //当 auth 中间件判定某个用户未认证,会返回一个 JSON 401 响应,或者,如果不是 Ajax 请求的话,将用户重定向到 login 命名路由(也就是登录页面)。
        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,

然后在后台并在web.php中使用此中间件,添加后台中间件

Route::prefix('admin')->namespace('Admin')->group(function () {
    //后台首页
    $this->get('login', 'LoginController@showLoginForm')->name('admin.login');
    $this->post('login', 'LoginController@login');
    $this->post('logout', 'LoginController@logout')->name('admin.logout');
    Route::middleware('auth.admin:admin')->name('admin.')->group(function () {
        Route::get('/', 'HomeController@index');
    });
});

 

7、创建后台首页控制器

此时我们的Admin\HomeController并未创建

创建后台首页路由

php artisan make:controller Admin/HomeController

增加一条路由规则,加载后台首页

public function index()
    {
//        dd('后台首页,当前管理员:' . auth('admin')->user()->name);
        return view('admin.index');
    }

 

8、创建后台首页与登录页模板

resources/view/admin/index.blade.php

resources/view/admin/login.blade.php

 

 

参考:

https://www.jianshu.com/p/ee8df298841e

标签:

给我留言