Challenge - 5 Problems
Raw Expression Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of raw expression in a query builder
What will be the output SQL query generated by this Laravel query builder code?
Laravel
$query = DB::table('users') ->select(DB::raw('count(*) as user_count')) ->toSql(); echo $query;
Attempts:
2 left
💡 Hint
Remember Laravel adds backticks around table names in the generated SQL.
✗ Incorrect
Laravel's query builder wraps table names with backticks and preserves raw expressions as-is. So the raw count(*) as user_count remains unchanged, and the table name is backticked.
❓ component_behavior
intermediate2:00remaining
Effect of raw expressions on query bindings
Given this Laravel query, what will be the value of the bindings array after execution?
Laravel
$query = DB::table('orders') ->whereRaw('price > ?', [100]) ->where('status', '=', 'paid'); $bindings = $query->getBindings();
Attempts:
2 left
💡 Hint
Bindings are collected in the order they appear in the query.
✗ Incorrect
The whereRaw adds a binding for 100 first, then the where adds a binding for 'paid'. So the bindings array is [100, 'paid'].
🔧 Debug
advanced2:00remaining
Why does this raw expression cause a syntax error?
Consider this Laravel query:
DB::table('products')
->select(DB::raw('SUM(price) AS total_price'))
->whereRaw('category = ?', 'electronics')
->get();
Why does this code cause an error?
Attempts:
2 left
💡 Hint
Check the expected argument types for whereRaw bindings.
✗ Incorrect
whereRaw expects the bindings as an array. Passing a string causes a type error.
📝 Syntax
advanced2:00remaining
Correct syntax for raw order by clause
Which option correctly orders users by a raw expression that calculates length of the name?
Laravel
DB::table('users')->orderByRaw(???)->get();Attempts:
2 left
💡 Hint
orderByRaw expects a string with the raw SQL expression.
✗ Incorrect
orderByRaw takes a string. Passing a bare expression or array causes errors.
🧠 Conceptual
expert3:00remaining
Understanding security risks with raw expressions
Which statement best explains the security risk when using raw expressions in Laravel queries?
Attempts:
2 left
💡 Hint
Think about how raw SQL is handled compared to parameter binding.
✗ Incorrect
Raw expressions bypass Laravel's query builder protections. If user input is concatenated directly, it can cause SQL injection.