Bird
0
0

You want to get a query parameter filter in Laravel but provide a default value of all if it is missing or empty. Which code correctly handles this?

hard📝 Application Q15 of 15
Laravel - Request and Response
You want to get a query parameter filter in Laravel but provide a default value of all if it is missing or empty. Which code correctly handles this?
A$filter = $request->query('filter') ?: 'all';
B$filter = $request->input('filter', 'all');
C$filter = $request->query('filter', 'all');
D$filter = $request->query('filter') ?? 'all';
Step-by-Step Solution
Solution:
  1. Step 1: Understand default value behavior in query()

    The second argument in query('filter', 'all') returns 'all' only if the parameter is missing, but not if empty.
  2. Step 2: Handle empty values as well

    Using $request->query('filter') ?: 'all' returns 'all' if the parameter is missing or empty (falsy).
  3. Step 3: Check other options

    $filter = $request->input('filter', 'all'); uses input() which includes POST data, not just query. $filter = $request->query('filter') ?? 'all'; uses null coalescing which does not treat empty string as missing.
  4. Final Answer:

    $filter = $request->query('filter') ?: 'all'; -> Option A
  5. Quick Check:

    Use ?: to handle missing or empty query params = C [OK]
Quick Trick: Use ?: to cover missing or empty query parameters [OK]
Common Mistakes:
  • Assuming default in query() covers empty strings
  • Using input() which mixes POST and query data
  • Using ?? which ignores empty strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes