orderBy() and order()

The orderBy() and order() methods define the sort direction of query results. Both accept a column and an optional sort direction, but differ in their default behavior:

  • orderBy() defaults to DESC – commonly used to show newest or latest entries first.
  • order() defaults to ASC – useful for alphabetical or oldest-first sorting.

Signature:

public function orderBy(string $field, string $direction = 'DESC'): self
public function order(string $field, string $direction = 'ASC'): self

Sort by Created Date (Newest First)

$db->orderBy('created_at');

Sort by Created Date (Oldest First)

$db->orderBy('created_at', 'ASC');

Alphabetical Order

$db->order('name');

Reverse Alphabetical Order

$db->order('name', 'DESC');

Multiple Sorts

Chaining both methods is allowed and builds a composite ORDER BY clause:

$db->order('type')->orderBy('created_at');

Validation Rules

  • Only safe column names are accepted (alphanumeric with dots or underscores).
  • Allowed directions: ASC, DESC (case-insensitive).
  • Raw SQL functions like RAND() are rejected unless explicitly marked as safe with [F].
  • Invalid input such as SLEEP(1) or 1=1 will throw an exception.

See Also