0
0
LaravelHow-ToBeginner · 4 min read

How to Use Query Builder in Laravel: Syntax and Examples

In Laravel, you use the DB::table() method to start a query builder instance. You can chain methods like select(), where(), and get() to build and execute database queries fluently.
📐

Syntax

The Laravel query builder starts with DB::table('table_name') to specify the table. You can chain methods like select() to choose columns, where() to filter rows, and get() to execute and fetch results.

Example parts:

  • DB::table('users'): Start query on 'users' table.
  • select('name', 'email'): Choose columns to retrieve.
  • where('id', 1): Filter rows where 'id' equals 1.
  • get(): Run the query and get results.
php
use Illuminate\Support\Facades\DB;

$users = DB::table('users')
    ->select('name', 'email')
    ->where('active', 1)
    ->get();
💻

Example

This example shows how to get all active users' names and emails from the database using Laravel's query builder.

php
<?php
use Illuminate\Support\Facades\DB;

$activeUsers = DB::table('users')
    ->select('name', 'email')
    ->where('active', 1)
    ->get();

foreach ($activeUsers as $user) {
    echo "Name: {$user->name}, Email: {$user->email}\n";
}
Output
Name: Alice, Email: alice@example.com Name: Bob, Email: bob@example.com
⚠️

Common Pitfalls

Common mistakes include forgetting to call get() or first() to execute the query, which results in no data returned. Another is mixing raw SQL strings without bindings, which can cause SQL injection risks.

Also, using where() incorrectly by passing wrong parameters or forgetting to chain methods properly can cause errors.

php
<?php
// Wrong: Missing get() to execute query
$users = DB::table('users')->where('active', 1);

// Right: Add get() to fetch results
$users = DB::table('users')->where('active', 1)->get();
📊

Quick Reference

MethodDescriptionExample
DB::table('table')Start a query on a tableDB::table('users')
select('col1', 'col2')Choose columns to retrieve->select('name', 'email')
where('col', value)Filter rows by condition->where('active', 1)
orderBy('col', 'asc|desc')Sort results->orderBy('created_at', 'desc')
get()Execute query and get all results->get()
first()Get first result only->first()
insert(array)Insert new record->insert(['name' => 'John'])
update(array)Update records->where('id', 1)->update(['active' => 0])
delete()Delete records->where('id', 1)->delete()

Key Takeaways

Start queries with DB::table('table_name') to specify the table.
Chain methods like select(), where(), and get() to build and run queries.
Always call get() or first() to execute the query and fetch results.
Avoid raw SQL strings without bindings to prevent security risks.
Use query builder methods for readable and safe database queries.