Query Builder

Introduction

The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.

Note: The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

Selects

Retrieving All Rows From A Table

  1. $users = DB::table('users')->get();
  2. foreach ($users as $user)
  3. {
  4. var_dump($user->name);
  5. }

Retrieving A Single Row From A Table

  1. $user = DB::table('users')->where('name', 'John')->first();
  2. var_dump($user->name);

Retrieving A Single Column From A Row

  1. $name = DB::table('users')->where('name', 'John')->pluck('name');

Retrieving A List Of Column Values

  1. $roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

  1. $roles = DB::table('roles')->lists('title', 'name');

Specifying A Select Clause

  1. $users = DB::table('users')->select('name', 'email')->get();
  2. $users = DB::table('users')->distinct()->get();
  3. $users = DB::table('users')->select('name as user_name')->get();

Adding A Select Clause To An Existing Query

  1. $query = DB::table('users')->select('name');
  2. $users = $query->addSelect('age')->get();

Using Where Operators

  1. $users = DB::table('users')->where('votes', '>', 100)->get();

Or Statements

  1. $users = DB::table('users')
  2. ->where('votes', '>', 100)
  3. ->orWhere('name', 'John')
  4. ->get();

Using Where Between

  1. $users = DB::table('users')
  2. ->whereBetween('votes', array(1, 100))->get();

Using Where Not Between

  1. $users = DB::table('users')
  2. ->whereNotBetween('votes', array(1, 100))->get();

Using Where In With An Array

  1. $users = DB::table('users')
  2. ->whereIn('id', array(1, 2, 3))->get();
  3. $users = DB::table('users')
  4. ->whereNotIn('id', array(1, 2, 3))->get();

Using Where Null To Find Records With Unset Values

  1. $users = DB::table('users')
  2. ->whereNull('updated_at')->get();

Order By, Group By, And Having

  1. $users = DB::table('users')
  2. ->orderBy('name', 'desc')
  3. ->groupBy('count')
  4. ->having('count', '>', 100)
  5. ->get();

Offset & Limit

  1. $users = DB::table('users')->skip(10)->take(5)->get();

Joins

The query builder may also be used to write join statements. Take a look at the following examples:

Basic Join Statement

  1. DB::table('users')
  2. ->join('contacts', 'users.id', '=', 'contacts.user_id')
  3. ->join('orders', 'users.id', '=', 'orders.user_id')
  4. ->select('users.id', 'contacts.phone', 'orders.price')
  5. ->get();

Left Join Statement

  1. DB::table('users')
  2. ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  3. ->get();

You may also specify more advanced join clauses:

  1. DB::table('users')
  2. ->join('contacts', function($join)
  3. {
  4. $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
  5. })
  6. ->get();

If you would like to use a "where" style clause on your joins, you may use the where and orWhere methods on a join. Instead of comparing two columns, these methods will compare the column against a value:

  1. DB::table('users')
  2. ->join('contacts', function($join)
  3. {
  4. $join->on('users.id', '=', 'contacts.user_id')
  5. ->where('contacts.user_id', '>', 5);
  6. })
  7. ->get();

Advanced Wheres

Parameter Grouping

Sometimes you may need to create more advanced where clauses such as "where exists" or nested parameter groupings. The Laravel query builder can handle these as well:

  1. DB::table('users')
  2. ->where('name', '=', 'John')
  3. ->orWhere(function($query)
  4. {
  5. $query->where('votes', '>', 100)
  6. ->where('title', '<>', 'Admin');
  7. })
  8. ->get();

The query above will produce the following SQL:

  1. select * from users where name = 'John' or (votes > 100 and title <> 'Admin')

Exists Statements

  1. DB::table('users')
  2. ->whereExists(function($query)
  3. {
  4. $query->select(DB::raw(1))
  5. ->from('orders')
  6. ->whereRaw('orders.user_id = users.id');
  7. })
  8. ->get();

The query above will produce the following SQL:

  1. select * from users
  2. where exists (
  3. select 1 from orders where orders.user_id = users.id
  4. )

Aggregates

The query builder also provides a variety of aggregate methods, such as count, max, min, avg, and sum.

Using Aggregate Methods

  1. $users = DB::table('users')->count();
  2. $price = DB::table('orders')->max('price');
  3. $price = DB::table('orders')->min('price');
  4. $price = DB::table('orders')->avg('price');
  5. $total = DB::table('users')->sum('votes');

Raw Expressions

Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:

Using A Raw Expression

  1. $users = DB::table('users')
  2. ->select(DB::raw('count(*) as user_count, status'))
  3. ->where('status', '<>', 1)
  4. ->groupBy('status')
  5. ->get();

Inserts

Inserting Records Into A Table

  1. DB::table('users')->insert(
  2. array('email' => '[email protected]', 'votes' => 0)
  3. );

Inserting Records Into A Table With An Auto-Incrementing ID

If the table has an auto-incrementing id, use insertGetId to insert a record and retrieve the id:

  1. $id = DB::table('users')->insertGetId(
  2. array('email' => '[email protected]', 'votes' => 0)
  3. );

Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".

Inserting Multiple Records Into A Table

  1. DB::table('users')->insert(array(
  2. array('email' => '[email protected]', 'votes' => 0),
  3. array('email' => '[email protected]', 'votes' => 0),
  4. ));

Updates

Updating Records In A Table

  1. DB::table('users')
  2. ->where('id', 1)
  3. ->update(array('votes' => 1));

Incrementing or decrementing a value of a column

  1. DB::table('users')->increment('votes');
  2. DB::table('users')->increment('votes', 5);
  3. DB::table('users')->decrement('votes');
  4. DB::table('users')->decrement('votes', 5);

You may also specify additional columns to update:

  1. DB::table('users')->increment('votes', 1, array('name' => 'John'));

Deletes

Deleting Records In A Table

  1. DB::table('users')->where('votes', '<', 100)->delete();

Deleting All Records From A Table

  1. DB::table('users')->delete();

Truncating A Table

  1. DB::table('users')->truncate();

Unions

The query builder also provides a quick way to "union" two queries together:

  1. $first = DB::table('users')->whereNull('first_name');
  2. $users = DB::table('users')->whereNull('last_name')->union($first)->get();

The unionAll method is also available, and has the same method signature as union.

Pessimistic Locking

The query builder includes a few functions to help you do "pessimistic locking" on your SELECT statements.

To run the SELECT statement with a "shared lock", you may use the sharedLock method on a query:

  1. DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

To "lock for update" on a SELECT statement, you may use the lockForUpdate method on a query:

  1. DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

Caching Queries

You may easily cache the results of a query using the remember or rememberForever method:

  1. $users = DB::table('users')->remember(10)->get();

In this example, the results of the query will be cached for ten minutes. While the results are cached, the query will not be run against the database, and the results will be loaded from the default cache driver specified for your application.

If you are using a supported cache driver, you can also add tags to the caches:

  1. $users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();