How to check user Permissions using Custom Middleware in Laravel



PHP Snippet 1:

class HasPermission
{

    public function handle($request, Closure $next,$permissions)
    {

        $permissions_array = explode('|', $permissions);
        foreach($permissions_array as $permission){
            if ($request->user()->hasPermission($permission)){
                return $next($request);
            }
        }    
       return redirect()->back();    
    }
}

PHP Snippet 2:

class HasPermission
{

    public function handle($request, Closure $next,$permissions)
    {

        $permissions_array = explode('|', $permissions);
        foreach($permissions_array as $permission){
            if (!$request->user()->hasPermission($permission)){
                return redirect()->back();                        
            }
        }    
        return $next($request);
    }
}

PHP Snippet 3:

class HasPermission
{

    public function handle($request, Closure $next, ...$permissions_array)
    {    
       //Function body from above without the explode part
    }
}

PHP Snippet 4:

function __construct()
{
   $this->middleware('auth');
   $this->middleware('HasPermission:Role_Read,Role_Update,Role_Delete');
}

PHP Snippet 5:

public static function user_permissions($user) {

$permissions=DB::table('permissions')->where('user_id', $user)->first();
return $permissions; 

}

PHP Snippet 6:

   if(Auth::guest())
    {
        return redirect('/');
    }

elseif(Functions::user_permissions(Auth::user()->id)->user_managment != 1) {

 return redirect('/');

} else {
    return $next($request);
}