我得到了User, Roles,Permissions和role_user, role_permission.
我想做的是:
- 在用户模式中检查请求用户的权限。
Laravel建议gate policy
进行授权。最好的方法是学习它:
https://laravel.com/docs/8.x/authorization
但是如果你想用你自己的方法。你可以使用中间件,并将其添加到你想要保护的所有路由中。
php artisan make:middleware MyauthMiddleware
把下面的代码放进去:
<?php
namespace AppHttpMiddleware;
use Closure;
class MyauthMiddleware
{
public function handle($request, Closure $next,$permission_id)
{
if (Auth::user()) { // if user is logined
// Do what you want from your tables.
// Here is the most important part you should use.
//I wrote sample bellow:
$roles = RoleUser::where('user_id',Auth::user()->id)->get();
foreach($roles as $role_user){
if($role_user->role->permision->id == $permission_id){
return $next($request);
}
}
}
return redirect('/');
}
然后在app/Http/Kernel.php
类的$middleware
属性中添加新的中间件类。
protected $routeMiddleware = [
//....
'myauthcheck' => AppHttpMiddlewareMyauthMiddleware::class,
];
然后在你的路由上设置中间件:
Route::group(['middleware' => 'myauthcheck:832'], function () {
//your routes here related to 832 permission_id
});
如果我让你正确,你正在寻找一种方式来查询你的数据库。不幸的是,你不能用Laravel的Eloquent ORM直接做到这一点,需要一些额外的努力,在我看来,这不是很有效。SQL:
就是这样SELECT `permissions`.* FROM `permissions` JOIN `role_permission` ON (`permissions`.`id` = `role_permission`.`permission_id`) WHERE `role_permission`.`role_id` IN (SELECT `role_id` FROM `user_role` WHERE `user_role`.`user_id` = $USER_ID)
我希望这对你有帮助。