Laravel多用户登录注册(例:3个用户,管理员,企业,普通用户)
在实际项目开发中,我们经常会遇到多种类型的用户认证问题,比如后台管理员,企业和前端普通用户3个用户。网上找的很多例子都是两个用户的登录,而且有些例子写的都是错的,那如何来完成此类功能呢,我们首先想到应该是中间件,接下来我就逐一跟大家分析。一、创建项目打开MAC自带终端,输入:Laravel new test,配置虚拟机test.com,打开浏览器访问此网址即可进入Laravel首页。二、数据...
在实际项目开发中,我们经常会遇到多种类型的用户认证问题,比如后台管理员,企业和前端普通用户3个用户。网上找的很多例子都是两个用户的登录,而且有些例子写的都是错的,那如何来完成此类功能呢,我们首先想到应该是中间件,接下来我就逐一跟大家分析。
一、创建项目
打开MAC自带终端,输入:Laravel new test,配置虚拟机test.com,打开浏览器访问此网址即可进入Laravel首页。
二、数据库配置
在MySQL管理软件中创建数据库testuser,并在.env文件中配置数据库。如:
三、前端普通用户(user,我们使用用户名登录)
1、终端执行命令:php artisan make:auth 生成用户认证所需的路由和模板。此时查看web.php发现路由已更新。
2、 接下来我们执行迁移命令:php artisan migrate生成数据表,然后在数据库中你刷新一下就会发现多了几张表。
3、再去刷新浏览器,页面的右上角多了登录和注册按钮,我们随即注册一个用户 user,注册成功跳转到首页。此时数据库中已插入一条数据。
4、接下来我们可以使用这个账号去登录了,由于Laravel默认的登录是使用邮箱的,所以这里我们需要在app\Http\Controllers\Auth\LoginController中添加如下代码设置默认登录使用用户名,当然对应模板的name也要改过来。
public function username()
{
return 'name';
}
5、测试:去前端登录页面,输入账号密码,可以看到如下界面:
至此,前端普通用户认证成功!
四、后台认证(admin,我们使用邮箱登录)
1、 先去web.php文件中配置路由组:
Route::prefix('admin')->group(function () {
Route::get('/', 'Admin\DashboardController@index');
});
2、生成后台首页控制器:php artisan make:controller Admin/DashboardController并创建index方法,里面直接打印管理员session,如:
public function index()
{
dd('后台首页,当前管理员:' . auth('admin')->user()->name);
}
3、创建管理员(admins)数据表
(1) 生成admins表的迁移文件:php artisan make:migration create_admins_table,
(2) 修改 database/migrations/*_create_admins_table.php 中的 up()方法,如:
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
终端执行php artisan migrate, 手动往数据表admins里面添加一条数据。
(3) 生成数据表模型:php artisan make:model Models/Admin,并修改app/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',
];
}
(4) 修改路由组,如下:
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::name('admin.')->group(function () {
$this->get('/', 'DashboardController@index');
});
});
(5) 新建管理员登录控制器:php artisan make:controller Admin/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.auth.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');
}
}
(6) 添加管理员认证,修改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',
// ],
],
(7) 新建登录模板 resources/views/admin/auth/login.blade.php ,我这里使用amazeui自带的登录模板,使用之前必须引入amazeui的样式。注意:修改登录提交的路由地址{{ route(‘admin.login’) }}。
通过命令:php artisan make:middleware AdminAuthMiddleware创建后台管理员中间件,并添加代码如下:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthMiddleware
{
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里面注册该中间件 ‘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 () {
$this->get('/', 'DashboardController@index');
});
});
刷新浏览器,进入后台登录页面,输入邮箱密码看到如下页面,说明管理员登录就大功告成啦。
至此,普通用户和管理员两个登录已完成。
五、企业后台登录(company,我们使用手机号登录)
1、首先我们定义企业后台路由,如下:
Route::prefix('company')->namespace('Company')->group(function () {
$this->get('login', 'LoginController@showLoginForm')->name('company.login');
$this->post('login', 'LoginController@login');
$this->post('logout', 'LoginController@logout')->name('company.logout');
Route::name('company.')->group(function () {
$this->get('/', 'CompanyController@index');
});
});
2、创建登录控制器 php artisan make:controller Company/LoginController
<?php
namespace App\Http\Controllers\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* 默认使用手机号登陆
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return 'mobile';
}
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/company';
protected $username;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest:company', ['except' => 'logout']);
$this->username = config('company.global.username');
}
/**
* 重写登录视图页面
* @author Holy
* @date 2018-04-02
* @return [type]
*/
public function showLoginForm()
{
return view('company.auth.login');
}
/**
* 自定义认证驱动
* @author Holy
* @date 2018-04-02
* @return [type]
*/
protected function guard()
{
return auth()->guard('company');
}
/**
* 企业后台退出跳转到后台登录页面
* 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('/company/login');
}
}
3、创建企业后台首页控制器:php artisan make:controller Company/CompanyController,直接打印session
public function index()
{
dd('企业后台首页,当前用户名:'.auth('company')->user()->name);
}
4、 创建企业(companies)数据表
(1) 生成companies表的迁移文件:php artisan make:migration create_companies_table,并添加如下代码:
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('mobile', 11);
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
(2) 执行迁移命令:php artisan migrate创建数据表companies,手动填充数据。
(3) 终端跑命令创建模型:php artisan make:model Models/Company
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Company extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
5、接下来去 config/auth.php 添加模型,如:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'company' => [
'driver' => 'session',
'provider' => 'companies',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'companies' => [
'driver' => 'eloquent',
'model' => App\Models\Company::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
6、 然后刷新页面,提示视图未加载。此刻,我们去创建视图模板:
7、 接下来,我们去创建企业中间件,终端执行命令:php artisan make:middleware CompanyAuthMiddleware,添加如下代码:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CompanyAuthMiddleware
{
/**
* 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('company/login');
}
}
return $next($request);
}
}
注册中间件:Kernel.php中添加:‘auth.company’=>\App\Http\Middleware\CompanyAuthMiddleware::class,
使用中间件:web.php中设置路由组,如下:
Route::prefix('company')->namespace('Company')->group(function () {
$this->get('login', 'LoginController@showLoginForm')->name('company.login');
$this->post('login', 'LoginController@login');
$this->post('logout', 'LoginController@logout')->name('company.logout');
Route::middleware('auth.company:company')->name('company.')->group(function () {
$this->get('/', 'CompanyController@index');
});
});
8、测试:刷新浏览器,输入手机号和密码登录,你就会看到成功的曙光:
更多推荐
所有评论(0)