时间:2021-07-01 10:21:17 帮助过:6人阅读
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::group(['prefix' => 'admin','namespace' => 'Admin'], function () {
Route::resource('dashboard', 'DashboardController');
});
});
管理员通过http://www.example.com/admin/dashboard/
可以访问,但不是管理员就不能访问,应该怎样做呢?
正在用的版本是laravel5.2,用entrust这个包的时候,控制角色的访问目录,思路要点大概是怎样?
比如:
管理员的路由是这样的:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::group(['prefix' => 'admin','namespace' => 'Admin'], function () {
Route::resource('dashboard', 'DashboardController');
});
});
管理员通过http://www.example.com/admin/dashboard/
可以访问,但不是管理员就不能访问,应该怎样做呢?
第一步,创建admin
中间件
// App\Http\Middleware\AdminMiddleware.php
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// 如果当前用户没有管理员角色,返回403
if ( ! $request->user()->hasRole('admin')) {
abort(403);
}
return $next($request);
}
}
第二步,注册admin
中间件
// App\Http\Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
第三步,在DashboardController
的构造器内注册刚刚创建的admin
中间件
// App\Http\Controller\DashboardController.php
class DashboardController extends Controller
{
// ...
/**
* constructor
*/
public function __construct()
{
$this->middleware('admin');
}
// ...
}