2

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.

2 Answers 2

3

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
});
6
  • Ok, i understand. But even if i do this. What do i have to write to check if user has (...) permission? I know how to check user role but permission has no pivot table to user so its kinda confusing.
    – Ser
    Mar 2, 2021 at 9:17
  • 1
    @ChrisServ I edited my answer and add some details. Check it again. Mar 2, 2021 at 9:33
  • 1
    For using this line $role->permission->id you should have relation hasMany to permission in Role Model. Mar 2, 2021 at 9:44
  • Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from roles where user_id = 1) What am i doing wrong?
    – Ser
    Mar 2, 2021 at 9:54
  • Use RoleUser model rather than Role class in my answer Mar 2, 2021 at 9:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.