Laravel Query Builder: CRUD Operations, Advanced Queries, and Performance Tips
This article provides a comprehensive guide to Laravel's query builder, covering basic CRUD commands, selective column retrieval, complex where clauses, joins, aggregations, raw expressions, inserts, updates, deletions, unions, locking mechanisms, and query caching with clear code examples for each feature.
The following guide demonstrates how to use Laravel's query builder to perform common database operations and more advanced queries.
Selects
$users = DB::table('users')->get();
foreach ($users as $user) {
var_dump($user->name);
} $user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name); $name = DB::table('users')->where('name', 'John')->pluck('name'); $roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name'); $users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();Adding Selects to an Existing Query
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
var_dump($users);Where Clauses
$users = DB::table('users')->where('votes', '>', 100)->get(); $users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John')->get(); $users = DB::table('users')->whereBetween('votes', array(1, 100))->get(); $users = DB::table('users')->whereNotBetween('votes', array(1, 100))->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('updated_at')->get();Order, Group, and Having
$users = DB::table('users')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();Offset & Limit
$users = DB::table('users')->skip(10)->take(5)->get();Joins
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get(); DB::table('users')->leftJoin('posts', 'users.id', '=', 'posts.user_id')->get(); DB::table('users')->join('contacts', function($join) {
$join->on('users.id', '=', 'contacts.user_id')
->orOn(...);
})->get();Nested Where Clauses
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();Aggregates
$count = DB::table('users')->count();
$maxPrice = DB::table('orders')->max('price');
$minPrice = DB::table('orders')->min('price');
$avgPrice = DB::table('orders')->avg('price');
$totalVotes = DB::table('users')->sum('votes');Raw Expressions
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();Increment / Decrement
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);Inserts
DB::table('users')->insert(['email' => '[email protected]', 'votes' => 0]); $id = DB::table('users')->insertGetId(['email' => '[email protected]', 'votes' => 0]); DB::table('users')->insert([
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
]);Updates
DB::table('users')->where('id', 1)->update(['votes' => 1]);Deletes
DB::table('users')->where('votes', '<', 100)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();Unions
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get();Locking
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();Caching Queries
$users = DB::table('users')->remember(10)->get();
$users = DB::table('users')->cacheTags(['people','authors'])->remember(10)->get();The article concludes with a brief motivational note and links to additional Laravel cheat‑sheets for storage, schema, and mail.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.