Liveview Sorting DB Collection and Rendering Problem (very basic)

Yes, as I mentioned before, String.to_existing_atom/1 is safe. The function does come with a caveat, though: because there is no way to guarantee the order in which modules are loaded, there are situations where, unless you have previously declared the atom somewhere in that module, the function may fail. See the docs.

I don’t think this will apply to your situation, though, as by the time this function is called the atom will almost certainly exist. Maybe you could get a weird case where the testbed list is empty and no module referencing the atom has been loaded yet, at least in development, but I’m not entirely sure.

However, I still recommend the case approach instead. Your code allows a malicious user to effectively pass in any atom. It is much safer to validate the possibilities up-front. For example, imagine, in the future, that you added a field to your schema which you did not want users to be able to sort by. Well, a malicious user could pass any atom into your function, including that particular field.

This might not sound so bad in this particular case, but it’s not hard to imagine similar code accidentally, say, leaking the password field from a User struct. Best to avoid this class of issues entirely and validate your inputs early.

def handle_event("sort_by_string", %{"field" => field}, socket) do
  field = case field do
    "hardware" -> :hardware
    "foo" -> :foo
    # ... etc
  end
  # ... the rest of your code
end

This is not the only way to validate your inputs. For example you could, equivalently, do this:

def handle_event("sort_by_string", %{"field" => field}, socket)
    when field in ["hardware", "foo"] do
  field = String.to_existing_atom(field)
  # ... the rest of your code
end