Database: Query Builder
Introduction
Laravel's 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.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
Retrieving Results
Retrieving All Rows From A Table
You may use the table
method on the DB
facade to begin a query. The table
method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get
method:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* @return Response
*/
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
The get
method returns an Illuminate\Support\Collection
containing the results where each result is an instance of the PHP stdClass
object. You may access each column's value by accessing the column as a property of the object:
foreach ($users as $user) {
echo $user->name;
}
Retrieving A Single Row / Column From A Table
If you just need to retrieve a single row from the database table, you may use the first
method. This method will return a single stdClass
object:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
If you don't even need an entire row, you may extract a single value from a record using the value
method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Retrieving A List Of Column Values
If you would like to retrieve a Collection containing the values of a single column, you may use the pluck
method. In this example, we'll retrieve a Collection of role titles:
$titles = DB::table('roles')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
You may also specify a custom key column for the returned Collection:
$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
echo $title;
}
Chunking Results
If you need to work with thousands of database records, consider using the chunk
method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure
for processing. This method is very useful for writing Artisan commands that process thousands of records. For example, let's work with the entire users
table in chunks of 100 records at a time:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
foreach ($users as $user) {
//
}
});
You may stop further chunks from being processed by returning false
from the Closure
:
DB::table('users')->orderBy('id')->chunk(100, function ($users) {
// Process the records...
return false;
});
If you are updating database records while chunking results, your chunk results could change in unexpected ways. So, when updating records while chunking, it is always best to use the chunkById
method instead. This method will automatically paginate the results based on the record's primary key:
DB::table('users')->where('active', false)
->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
}
});
When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.
Aggregates
The query builder also provides a variety of aggregate methods such as count
, max
, min
, avg
, and sum
. You may call any of these methods after constructing your query:
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
You may combine these methods with other clauses:
$price = DB::table('orders')
->where('finalized', 1)
->avg('price');
Determining If Records Exist
Instead of using the count
method to determine if any records exist that match your query's constraints, you may use the exists
and doesntExist
methods:
return DB::table('orders')->where('finalized', 1)->exists();
return DB::table('orders')->where('finalized', 1)->doesntExist();
Selects
Specifying A Select Clause
You may not always want to select all columns from a database table. Using the select
method, you can specify a custom select
clause for the query:
$users = DB::table('users')->select('name', 'email as user_email')->get();
The distinct
method allows you to force the query to return distinct results:
$users = DB::table('users')->distinct()->get();
If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect
method:
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
Raw Expressions
Sometimes you may need to use a raw expression in a query. To create a raw expression, you may use the DB::raw
method:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.