概述
laraveli添加一个或多个用户表,以admin为例。。
部分文件内容可能需要根据实际情况修改
创建一个Admin模型
php artisan make:model Admin -m
编写admins表字段
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
编辑admin模型
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
/**
* @property int $id
* @property CarbonCarbon $created_at
* @property CarbonCarbon $updated_at
*/
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'password','remember_token'
];
protected $hidden = [
'password','remember_token'
];
}
修改auth.php配置文件
'guards' => [
...
'admin' => [
'driver' => 'session',
'provider' => 'admins'
]
],
'providers' => [
...
'admins' => [
'driver' => 'eloquent',
'model' => AppAdmin::class,
]
],
在app/Http/Controllers下创建目录Admin/Auth
在Admin目录下创建文件HomeController.php(这个文件用来测试登录成功后的跳转页面)
namespace AppHttpControllersAdmin;
use AppHttpControllersController;
use IlluminateHttpRequest;
class HomeController extends Controller
{
/**
* HomeController constructor.
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* @return IlluminateHttpResponse
*/
public function index()
{
return view('admin.home');
}
}
使用命令生成一个Request
php artisan make:request AdminLoginRequest
此时在app/Http/Request目录下便生成了这个文件,然后编辑这个文件
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class AdminLoginRequest extends FormRequest
{
/**
* 确定用户是否有权发出此请求.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* 获取适用于请求的验证规则.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'password' => ['required', 'min:6'] //密码必须,最小长度为6
];
}
}
在Admin/Auth目录下创建文件LoginController.php
namespace AppHttpControllersAdminAuth;
use AppHttpControllersController;
use AppHttpRequestsAdminLoginRequest;
use IlluminateSupportFacadesAuth;
class LoginController extends Controller
{
public function showLoginForm()
{
return view('admin.auth.login');
}
public function postLogin(AdminLoginRequest $loginRequest)
{
$data = $loginRequest->only('name', 'password');
$result = Auth::guard('admin')->attempt($data, true);
if ($result) {
return redirect(route('admin.home'));
} else {
return redirect()->back()
->with('name', $loginRequest->get('name'))
->withErrors(['name' => '用户名或密码错误']);
}
}
public function postLogout()
{
Auth::guard('admin')->logout();
return redirect(route('admin.login.show'));
}
}
添加路由。打开app/providers/RouteServiceProvider.php
在方法mapWebRoutes()方法后面增加一个方法
protected function mapAdminWebRoutes()
{
Route::middleware('web')
->prefix('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
}
在map()方法里调用上面增加的方法
public function map()
{
$this->mapApiRoutes();
$this->mapAdminWebRoutes();//调用新增的方法
$this->mapWebRoutes();
}
在routes目录下增加一个路由文件admin.php
Route::get('login','AdminAuthLoginController@showLoginForm')
->middleware('guest:admin')
->name('admin.login.show');
Route::get('/','AdminHomeController@index')
->name('admin.home');
Route::post('login','AdminAuthLoginController@postLogin')
->middleware('guest:admin')
->name('admin.login.post');
Route::post('logout','AdminAuthLoginController@postLogout')
->middleware('auth:admin')
->name('admin.logout');
把home.blade.php复制到resources/views/admin下
把layouts/app.blade.php复制为layouts/admin.blade.php,修改相应的地方
@guest('admin')
admin Login@else
{{ Auth::guard('admin')->user()->name }}
@endguest
把login.blade.php复制到admin/Auth目录下
@extends('layouts.admin')
@section('content')
{{ csrf_field() }}
E-Mail Address
value="{{ old('name') }}" required autofocus>
@if ($errors->has('name'))
{{ $errors->first('name') }}
@endif
Password
@if ($errors->has('password'))
{{ $errors->first('password') }}
@endif
Login
@endsection
数据填充
php artisan make:seed AdminsTableSeeder
编辑AdminsTableSeeder.php
public function run()
{
AppAdmin::insert([
'name'=>'yzha5',
'password'=> bcrypt('123456')
]);
}
DatabaseSeeder.php
$this->call(AdminsTableSeeder::class);
文件上传至服务器,登入服务器,执行填充命令
php artisan migrate
php artisan db:seed
此时,直接打开app/Exceptions/Handle.php
重写unauthenticated()方法。
use IlluminateSupportFacadesRoute;
protected function unauthenticated($request, AuthenticationException $exception)
{
return starts_with(Route::currentRouteName(), 'admin')
? redirect(route('admin.login.show'))
: parent::unauthenticated($request, $exception);
}
完善一下
以上代码,当admin登录后,再次访问/admin/login这个URI时,会自动跳转到/home这个URI,这是因为guest这个中间件默认跳转到了/home,也就是middleware目录下的RedirectIfAuthenticated.php这个文件。
解决方法为:
创建一个中单件,名为:RedirectIfAdminAuthenticated
php artisan make:middleware RedirectIfAdminAuthenticated
编辑这个文件:
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class RedirectIfAdminAuthenticated
{
/**
* Handle an incoming request.
*
* @param $request
* @param Closure $next
* @param null $guard
* @return IlluminateHttpRedirectResponse|IlluminateRoutingRedirector|mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/admin');
}
return $next($request);
}
}
在Kernel.php中添加一行
protected $routeMiddleware = [
...
'admin.guest' => AppHttpMiddlewareRedirectIfAdminAuthenticated::class,
...
];
更改admin路由,将guest:admin改为admin.guest:admin
Route::get('login','AdminAuthLoginController@showLoginForm')
->middleware('admin.guest:admin')
->name('admin.login.show');
Route::post('login','AdminAuthLoginController@postLogin')
->middleware('admin.guest:admin')
->name('admin.login.post');
最后
以上就是潇洒路灯为你收集整理的php 多用户登录,laravel 实现多用户体系登录的全部内容,希望文章能够帮你解决php 多用户登录,laravel 实现多用户体系登录所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复