laravel auth认证栏目

修改laravel auth表为admins表

需求

因为users表被我用来做用户数据了,而laravel中auth认证默认用的是users表

所以,我就又建了一张admins表,表结构是laravel的默认users结构,打算用这张表来做后台登录

生成认证

php artisan make:auth

修改模板

这里就不多说了

修改$redirectTo属性

因为我一会会把HomeController和home.blade.php都删掉

protected $redirectTo = '/';

修改validator验证

修改 RegisterController email.unique后面的users为admins

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:admins',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

修改create

User模型改为Admin

protected function create(array $data)
    {
        return Admin::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

修改config/auth.php

App\Users::class改为App\Models\Admin::class,

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

/register注册一个账号

删除自带路由自己写

注释Auth::routes();重写路由,因为后台只需要登录和退出登记即可,不能有注册,以及其他的动作

//Auth::routes();

Route::group(['namespace' => 'Auth'], function () {
    Route::get('login','LoginController@showLoginForm')->name('login.create');
    Route::post('login','LoginController@login')->name('login.store');
    Route::post('logout','LoginController@logout')->name('logout');
});

好了..用你之前注册的账号试试登录吧

laravel auth多用户表登录

建立Admin模型

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

增加auth.app中providers数组

增加了admins

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

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

增加后端AuthController

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AuthController 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 = '/admins';

    /**
     * 重写后台登录视图加载
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function showLoginForm ()
    {
        if (authAdmin()) {
            return redirect(route('admin.index'));
        }

        return view('admin.auth.login');
    }

    /**
     * 自定义认证驱动
     *
     * @return mixed
     */
    protected function guard ()
    {

        return auth()->guard('admin');
    }

    /**
     * 退出登录
     * 
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout (Request $request)
    {
        $this->guard()->logout();

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

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

        return redirect(route('admin.login'));
    }

    /**
     * 指定用name登录
     *
     * @return string
     */
    public function username ()
    {
        return config('app.login_username');
    }
}

将验证写到Helpers(自定义方法)

if (! function_exists('authAdmin')) {
    /**
     * 判断后台用户是否登录
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    function authAdmin ()
    {
        return auth('admin')->user();
    }
}

增加中间件

namespace App\Http\Middleware;

use Closure;
class AdminAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$guard = null)
    {

        if( !authAdmin() ){
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('admins/login');
            }
        }

        return $next($request);
    }
}

中间件注册到Kernel.php的$routeMiddleware数组

protected $routeMiddleware = [
        //..........
        'auth.admin' => \App\Http\Middleware\AdminAuthMiddleware::class,
    ];

自定义guards

'guards' => [
    //.....
        //自定义后端的auth guards
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ]
]

路由

Route::group(['namespace' => 'Admin','prefix' => 'admins'], function () {
    Route::get('/login','AuthController@showLoginForm')->name('admin.login');
    Route::post('/login', 'AuthController@login')->name('admin.login');
});
Route::group(['namespace' => 'Admin','prefix' => 'admins','middleware' => 'auth.admin'], function () {
    Route::get('/','IndexController@index')->name('admin.index');
    Route::post('/logout','AuthController@logout')->name('admin.logout');
});

修改退出登录表单

因为这里的退出登录是提交组织a标签,提交form的

 <a href="{{ route('admin.logout') }}"
                               onclick="event.preventDefault();
                                document.getElementById('logout-form').submit();"
                               class="dropdown-item notify-item">
                                <i class="zmdi zmdi-power"></i> <span>退出登录</span>
                            </a>
                            <form id="logout-form" action="{{ route('admin.logout') }}" method="POST"
                                  style="display: none;">
                                {{ csrf_field() }}
                            </form>