Search code examples
phplaravellaravel-5.3laravel-5.4laravel-5.5

Trying to decrease a method complexity with if and else


My code is below to fetch all roles with a condition to include with clause.

public function GetRoles($IsParentRoleRelationNeeded) {
    try {
        if($IsParentRoleRelationNeeded) {
            $Roles =  RoleModel
                ::select("RoleID", "Role", "IsDefault", "ParentRoleID")
                ->with(["ParentRole" => function($query) {
                    $query->select("RoleID", 'Role', "ParentRoleID");
                }])
                ->get();
        }
        else {
            $Roles =  RoleModel
                ::select("RoleID", "Role", "IsDefault", "ParentRoleID")
                ->get();
        }
        return $Roles
    } catch (Exception $ex) {
        return $ex;
    }
}

Now, I am trying to modify the code to add a union statement but conditionally.

Union Statement is here:

$Roles =  RoleModel::where("RoleID", 1)->first();

Below will be the function signature.

public function GetRoles($IsParentRoleRelationNeeded, $IsUnionClauseNeeded) {
    try {
        if($IsParentRoleRelationNeeded) {
            $Roles =  RoleModel
                ::select("RoleID", "Role", "IsDefault", "ParentRoleID")
                ->with(["ParentRole" => function($query) {
                    $query->select("RoleID", 'Role', "ParentRoleID");
                }])
                ->get();
        }
        else {
            $Roles =  RoleModel
                ::select("RoleID", "Role", "IsDefault", "ParentRoleID")
                ->get();
        }
        return $Roles
    } catch (Exception $ex) {
        return $ex;
    }
}

My question is: Do I need more if else to add union clause?


Solution

  • public function GetRoles($IsParentRoleRelationNeeded, $IsUnionClauseNeeded) {
           $Roles = RoleModel::select("RoleID", "Role", "IsDefault", "ParentRoleID"); // returns query builder
    
           if($IsParentRoleRelationNeeded) 
                 $Roles->with(["ParentRole" => function($query) {
                       $query->select("RoleID", 'Role', "ParentRoleID");
                  }]);
    
           if($IsUnionClauseNeeded)
                 $Roles->where("RoleID", 1);
    
    
            try {
                return $Roles->get(); // execute query
            } catch (Exception $ex) {
                return $ex;
            }
    }
    

    Yes also refactor your code like this.

    You might find this useful Laravel REST API with query parameters

    If your doing this to add options to your REST endpoints then you might want to look into GRAPHQL

    Also you should read the laravel docs, you might find alot of the framework features useful for avoiding this type of code. Honestly the above code should be avoided if possible, you can break things down into query scopes and other things.