I'm using make:auth method in laravel 5.4. Now, I want to change the behavior of the Register option. I want to have the register option only for users who logged in as Admin and for other users the register option should be disabled. The original version allows you to register before being authenticated. I want to use this register option to make admin to add new users. I tried option of authenticating user and redirect to register page in home.blade.php but it doesn't work. I am learning laravel for my new project.So any expert advice on how to proceed.
2条回答 默认 最新
- dongmei9508 2017-04-07 17:23关注
Currently there's a method like this in
App\Http\Controllers\Auth\RegisterController
public function __construct() { $this->middleware('guest'); }
This is currently making it so that only users who are not logged in can access the page. Instead, let's change that to meet the needs of one of your criteria:
public function __construct() { $this->middleware('auth'); }
Great, now they must be logged in to access it. But what about being an Admin? Let's make that Middleware, now:
php artisan make:middelware AdminMiddleware
Now let's open the file at
App\Http\Middleware\AdminMiddleware
and make some adjustments.Note I have to make some assumptions about your codebase here.
public function handle($request, Closure $next) { if ( auth()->check() && auth()->user()->hasRole('admin')) { return $next($request); } return redirect('/'); }
Next, let's register our application middleware. Open up
App\Http\Kernel.php
and scroll to the bottom:protected $routeMiddleware = [ 'admin' => \App\Http\Middleware\AdminMiddleware::class, // <--add this 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ];
Finally let's go back to
App\Http\Controllers\Auth\RegisterController
and update ourconstruct
function to utilize this middleware:public function __construct() { $this->middleware(['auth', 'admin']); }
Now your user must be logged in, and they also must have a role of
admin
.There's surely shorter ways to get this done, but this is a method that I prefer as it will help you from repeating yourself (DRY programming).
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 乌班图ip地址配置及远程SSH
- ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
- ¥15 PSPICE制作一个加法器
- ¥15 javaweb项目无法正常跳转
- ¥15 VMBox虚拟机无法访问
- ¥15 skd显示找不到头文件
- ¥15 机器视觉中图片中长度与真实长度的关系
- ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
- ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
- ¥15 java 的protected权限 ,问题在注释里