Refactor search code in controllers