← PHP / Laravel · Contents

PHP-003 / Intermediate

Passing user-provided column names to orderBy

A03:2021 Injection · CWE-89 SQL Injection

Why is this a problem?

Identifiers such as column names cannot be bound as parameters; an allowlist is necessary. Subquery injection is also possible.

How to fix it

php
$allowed = ['created_at', 'title'];
$sort = in_array($request->sort, $allowed, true) ? $request->sort : 'created_at';
$posts = Post::orderBy($sort, 'desc')->get();

Further reading