如果用户是管理员,我想要验证一些路由。
explode()
现在,我在Controller中创建了它:
Route::get( '/user/{data}', 'UserController@getData' );
Route::post( '/user/{data}', 'UserController@postData' );
我想用Route :: group制作它,但是我怎么能在routes.php中做到这一点?
答案 0 :(得分:4)
您可create middleware检查用户是否为管理员:
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
在Kernel.php
注册:
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
然后将其应用于路线组:
Route::group(['middleware' => 'is.admin'], function () {
Route::get('/user/{data}', 'UserController@getData');
Route::post('/user/{data}', 'UserController@postData');
});
答案 1 :(得分:0)
您可以指定路由组并为其提供中间件
https://laravel.com/docs/5.3/routing#route-groups
https://laravel.com/docs/5.3/middleware
https://laravel.com/docs/5.3/middleware#assigning-middleware-to-routes
示例:
routes.php文件
Route::group(['middleware' => 'admin'], function () {
Route::get( '/user/{data}', 'UserController@getData' );
Route::post( '/user/{data}', 'UserController@postData' );
});
应用程序/ HTTP /中间件/ admin.php的
<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
public function handle($request, Closure $next)
{
if ( Auth::user()->permission !== 'admin' ) {
//
} else {
//
}
}
}