Laravel创建自定义中间件以通过路由检查用户权限

时间:2019-05-17 17:43:13

标签: php laravel

我想创建一个自定义中间件,以检查是否允许我的用户进入教室。与教室相关的路由应受ClassRoom中间件保护,以在重定向到控制器之前检查用户权限。

这是教室路线组:

Route::group(['prefix' => 'classroom/{classroom_id}', 'namespace' => 'Classroom', 'as' => 'classroom.'], function(){
    Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});

这是检查权限的代码:

    $classroom = ClassRoom::findOrFail($classroom_id);

        $ok = false;
        foreach ($classroom->users as $classroom_user) {
          if ($classroom_user->id == user()->id) {
            $ok = true;
          }
        }

        if (!$ok) {
          return redirect()->route('user.classrooms.index');
        }

2 个答案:

答案 0 :(得分:1)

运行命令:

php artisan make:middleware CheckPermission

您的中间件:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

       // apply your permission logic here

        return $next($request);
    }
}

app / Http / Kernel.php

protected $routeMiddleware = [
    ... ,
    'check-permission' => \App\Http\Middleware\CheckPermission::class,
];

在路由文件(web.php)

Route::group(['middleware' => ['check-permission'], 'prefix' => 'classroom/{classroom_id}', 'namespace' => 'Classroom', 'as' => 'classroom.'], function(){
    Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});

答案 1 :(得分:0)

要在laravel中创建中间件,请使用php artisan make:middleware YourCustomMiddleWare

然后,您需要在受保护的routeMiddleware数组中的app / Http / Kernel.php中注册它

您像常规中间件一样将其添加到路由

https://laravel.com/docs/5.8/middleware