laravel的entrust这个包,控制角色的访问目录,思路要点大概是怎样?

WBOY
Release: 2016-06-06 20:10:45
Original
1199 people have browsed it

正在用的版本是laravel5.2,用entrust这个包的时候,控制角色的访问目录,思路要点大概是怎样?
比如:
管理员的路由是这样的:

<code>Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::group(['prefix' => 'admin','namespace' => 'Admin'], function () {
        Route::resource('dashboard', 'DashboardController');
     });
});</code>
Copy after login
Copy after login

管理员通过http://www.example.com/admin/dashboard/
可以访问,但不是管理员就不能访问,应该怎样做呢?

回复内容:

正在用的版本是laravel5.2,用entrust这个包的时候,控制角色的访问目录,思路要点大概是怎样?
比如:
管理员的路由是这样的:

<code>Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::group(['prefix' => 'admin','namespace' => 'Admin'], function () {
        Route::resource('dashboard', 'DashboardController');
     });
});</code>
Copy after login
Copy after login

管理员通过http://www.example.com/admin/dashboard/
可以访问,但不是管理员就不能访问,应该怎样做呢?

第一步,创建admin中间件

<code>// 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);
    }
}
</code>
Copy after login

第二步,注册admin中间件

<code>// 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,
];
</code>
Copy after login

第三步,在DashboardController的构造器内注册刚刚创建的admin中间件

<code>// App\Http\Controller\DashboardController.php

class DashboardController extends Controller
{
    // ...

    /**
     * constructor
     */
    public function __construct()
    {
        $this->middleware('admin');
    }


    // ...
}</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!