I got User, Roles ,Permissions and role_user, role_permission.
What I want to do is:
- check in User modal what the request user his permissions are.
I got User, Roles ,Permissions and role_user, role_permission.
What I want to do is:
Laravel suggest gate policy for authorization. The best method is learn it:
https://laravel.com/docs/8.x/authorization
But if you want to work with your own method.you can use a middleware and add it to all routes you want to protect them.
php artisan make:middleware MyauthMiddleware
Put this code in it:
<?php
namespace App\Http\Middleware;
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('/');
}
Then add the new middleware class in the $middleware property of your app/Http/Kernel.php class.
protected $routeMiddleware = [
//....
'myauthcheck' => \App\Http\Middleware\MyauthMiddleware::class,
];
Then set the middelware on your route:
Route::group(['middleware' => 'myauthcheck:832'], function () {
//your routes here related to 832 permission_id
});
If I got you right, you are looking for a way to query on your database. Unfortunately you can't do this with Laravel's Eloquent ORM directly and needs some additional effort which is not very efficient in my opinion. So this is the way with 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)
I hope it'd help you.