Bird
Raised Fist0
Laravelframework~10 mins

Select queries in Laravel - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Select queries
Start
↓
Build Query
↓
Add Select Columns
↓
Execute Query
↓
Fetch Results
↓
Use Data
↓
End
This flow shows how Laravel builds and runs a select query step-by-step, from starting the query to getting results.
Execution Sample
Laravel
use Illuminate\Support\Facades\DB;

$users = DB::table('users')
    ->select('id', 'name')
    ->where('active', 1)
    ->get();
This code selects the 'id' and 'name' columns from the 'users' table where 'active' is 1, then fetches the results.
Execution Table
StepActionQuery StateResult/Output
1Start query builder for 'users' tableQuery builder initialized for 'users'No output yet
2Add select columns 'id', 'name'Select columns set to ['id', 'name']No output yet
3Add where condition 'active' = 1Select columns set to ['id', 'name'] and where active = 1No output yet
4Execute get() to fetch resultsFinal SQL: SELECT id, name FROM users WHERE active = 1Query sent to database
5Fetch results from databaseResults received as collection of user recordsCollection of users with id and name where active=1
6Use data in applicationData ready for useUsers data accessible in $users variable
💡 Query executed and results fetched; process ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
$usersundefinedundefinedundefinedCollection of user recordsCollection of user records
Key Moments - 2 Insights
Why do we chain methods like select() and where() instead of writing one big query?
Laravel's query builder uses method chaining to build queries step-by-step, making it easier to read and modify. See execution_table steps 2 and 3 where select and where are added separately before execution.
What does get() do in the query?
The get() method executes the built query and fetches the results from the database. Before get(), no query is run (see execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the query state after step 3?
ASelect columns set to ['id', 'name'] and where active=1
BQuery builder initialized for 'users' only
CFinal SQL executed
DResults received from database
💡 Hint
Check the 'Query State' column at step 3 in the execution_table.
At which step does the actual database query run?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look for the step where 'Final SQL' is mentioned in the execution_table.
If we remove the select() method, what will the query select by default?
AOnly 'id' column
BNo columns, query fails
CAll columns (*)
DOnly 'name' column
💡 Hint
Laravel defaults to selecting all columns if select() is not specified.
Concept Snapshot
Laravel Select Queries:
- Start with DB::table('table_name')
- Chain ->select('col1', 'col2') to pick columns
- Add ->where('col', value) for conditions
- Call ->get() to run query and fetch results
- Without select(), all columns (*) are fetched by default
Full Transcript
This visual execution shows how Laravel builds a select query step-by-step. First, the query builder starts with the users table. Then, select columns 'id' and 'name' are added. Next, a where condition filters active users. The get() method runs the SQL query and fetches results. The users data is then ready to use. Variables like $users hold the fetched data after execution. Key points include method chaining for building queries and get() triggering the database call.

Practice

(1/5)
1. What does the select() method do in a Laravel query builder?
easy
A. It specifies which columns to retrieve from the database.
B. It inserts new data into the database.
C. It deletes rows from the database table.
D. It updates existing records in the database.

Solution

  1. Step 1: Understand the purpose of select()

    The select() method tells Laravel which columns you want to get from the database table.
  2. Step 2: Compare with other query methods

    Methods like insert(), delete(), and update() perform different actions, not selecting columns.
  3. Final Answer:

    It specifies which columns to retrieve from the database. -> Option A
  4. Quick Check:

    select() chooses columns [OK]
Hint: Remember: select() picks columns, not rows or actions [OK]
Common Mistakes:
  • Confusing select() with insert() or update()
  • Thinking select() deletes data
  • Assuming select() fetches all columns by default
2. Which of the following is the correct syntax to select the columns 'name' and 'email' from the 'users' table using Laravel's query builder?
easy
A. DB::table('users')->select(['name', 'email'])->get();
B. DB::table('users')->select('name' & 'email')->get();
C. DB::table('users')->select('name, email')->get();
D. DB::table('users')->select('name' + 'email')->get();

Solution

  1. Step 1: Check the correct way to pass multiple columns

    Laravel's select() accepts an array of column names to select multiple columns.
  2. Step 2: Analyze each option's syntax

    DB::table('users')->select('name, email')->get(); uses select('name, email'), which selects a single column named 'name, email'. Options B and D use invalid operators & and +. DB::table('users')->select(['name', 'email'])->get(); correctly uses an array ['name', 'email'].
  3. Final Answer:

    DB::table('users')->select(['name', 'email'])->get(); -> Option A
  4. Quick Check:

    Use array for multiple columns in select() [OK]
Hint: Use array syntax for multiple columns in select() [OK]
Common Mistakes:
  • Passing multiple strings without array
  • Using operators like + or & inside select()
  • Forgetting to call get() to execute query
3. What will be the output of the following Laravel query?
DB::table('products')->select('name')->where('price', '>', 100)->get();
medium
A. All products with price greater than 100, showing all columns.
B. All products with price less than or equal to 100, showing only their names.
C. All products with price greater than 100, showing only their names.
D. Syntax error due to incorrect where clause.

Solution

  1. Step 1: Understand the where condition

    The query filters products where the price is greater than 100.
  2. Step 2: Understand the select clause

    Only the 'name' column is selected, so only product names will be returned.
  3. Final Answer:

    All products with price greater than 100, showing only their names. -> Option C
  4. Quick Check:

    where('price', '>', 100) filters price > 100 [OK]
Hint: where() filters rows; select() chooses columns [OK]
Common Mistakes:
  • Confusing > with < in where clause
  • Expecting all columns instead of selected ones
  • Thinking where() causes syntax error here
4. Identify the error in this Laravel query:
DB::table('orders')->select('id', 'total')->where('status' = 'pending')->get();
medium
A. Using '=' instead of '==' in where clause.
B. Using '=' instead of ',' to separate arguments in where().
C. Missing semicolon at the end of the query.
D. select() cannot take multiple columns.

Solution

  1. Step 1: Check the where clause syntax

    The where method expects two arguments separated by a comma, not an assignment with '='.
  2. Step 2: Identify the correct syntax

    The correct syntax is where('status', 'pending'), not where('status' = 'pending').
  3. Final Answer:

    Using '=' instead of ',' to separate arguments in where(). -> Option B
  4. Quick Check:

    where() needs comma between arguments [OK]
Hint: Use comma, not =, between where() arguments [OK]
Common Mistakes:
  • Using = instead of comma in where()
  • Confusing assignment with comparison
  • Thinking select() can't take multiple columns
5. You want to get the 'id' and 'email' of users who are active and have verified their email. Which Laravel query correctly does this?
hard
A. DB::table('users')->select(['id', 'email'])->where('active' = 1)->where('email_verified' = 1)->get();
B. DB::table('users')->select('id', 'email')->where('active' == 1 && 'email_verified' == 1)->get();
C. DB::table('users')->select(['id', 'email'])->where('active', '=', 1, 'email_verified', '=', 1)->get();
D. DB::table('users')->select(['id', 'email'])->where(['active' => 1, 'email_verified' => 1])->get();

Solution

  1. Step 1: Understand filtering multiple conditions

    Laravel allows passing an associative array to where() to filter multiple columns with AND logic.
  2. Step 2: Analyze each option

    DB::table('users')->select(['id', 'email'])->where(['active' => 1, 'email_verified' => 1])->get(); correctly uses where(['active' => 1, 'email_verified' => 1]). DB::table('users')->select('id', 'email')->where('active' == 1 && 'email_verified' == 1)->get(); uses invalid syntax with == and && inside where(). DB::table('users')->select(['id', 'email'])->where('active', '=', 1, 'email_verified', '=', 1)->get(); passes too many arguments to a single where(). DB::table('users')->select(['id', 'email'])->where('active' = 1)->where('email_verified' = 1)->get(); uses = instead of , to separate where() arguments, causing syntax error.
  3. Final Answer:

    DB::table('users')->select(['id', 'email'])->where(['active' => 1, 'email_verified' => 1])->get(); -> Option D
  4. Quick Check:

    Use array in where() for multiple AND conditions [OK]
Hint: Use array in where() for multiple AND filters [OK]
Common Mistakes:
  • Using invalid operators inside where()
  • Passing too many arguments to where()
  • Not using array for multiple conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard