$users = DB::table('users')->get();
foreach ($users as $user) {
var_dump($user->username);
}
$user = DB::table('users')->where('username', 'john')->first();
var_dump($user->username);
$username = DB::table('users')->where('username', 'john')->pluck('name');
$users = DB::table('users')->select('username', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as username')->get();
$users = DB::table('users')->where('id', '>', 10)->get();
$users = DB::table('users')
->where('id', '>', 10)
->orWhere('username', 'john')
->get();
$users = DB::table('users')
->whereBetween('id', array(1, 10))->get();
$users = DB::table('users')
->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
->whereNotIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
->whereNull('display_name')->get();
DB::table('users')
->where('username', '=', 'john')
->orWhere(function($query) {
$query->where('id', '>', 10)
->where('status', '=', '1');
})
->get();
The query above will produce the following SQL:
select * from users where username = 'john' or (id > 10 and status = '1')
$users = DB::table('users')
->orderBy('username', 'desc')
->groupBy('role_id')
->having('role_id', '>', 1)
->get();
$users = DB::table('users')
->orderBy('rand()')
->limit(10)
->get();
$users = DB::table('users')->skip(10)->take(5)->get();
The query builder may also be used to write join statements. Take a look at the following examples:
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->select('users.id', 'username')
->get();
DB::table('users')
->leftJoin('roles', 'role_id', '=', 'posts.id')
->get();
The query builder also provides a variety of aggregate methods, such as count
, max
, min
, avg
, and sum
.
$users = DB::table('users')->count();
$id = DB::table('users')->max('id');
$id = DB::table('users')->min('id');
$id = DB::table('users')->avg('id');
$id = DB::table('users')->sum('id');
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:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
DB::table('users')->insert(
array('email' => 'john@example.com', 'status' => 1)
);
If the table has an auto-incrementing id, use insertGetId to insert a record and retrieve the id:
$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'status' => 1)
);
DB::table('users')->insert(array(
array('email' => 'foo@example.com', 'status' => 1),
array('email' => 'bar@example.com', 'status' => 1),
));
DB::table('users')
->where('id', 1)
->update(array('username' => 'foo'));
DB::table('users')->where('id', '<', 10)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();