Laravel Query Builder

Laravel Query Builder

Laravel's Query Builder provides a fluent interface for building and executing SQL queries without writing raw SQL.

1 - Basic Queries

use Illuminate\Support\Facades\DB;

// Select all
$users = DB::table('users')->get();

// Select specific columns
$users = DB::table('users')->select('name', 'email')->get();

// Get a single row
$user = DB::table('users')->where('email', '[email protected]')->first();

// Get a single value
$count = DB::table('posts')->where('published', true)->count();
$max   = DB::table('orders')->max('total');

2 - Where Clauses

DB::table('posts')
    ->where('published', true)
    ->where('views', '>', 100)
    ->orWhere('featured', true)
    ->get();

// whereIn / whereNotIn
DB::table('posts')->whereIn('status', ['published', 'featured'])->get();

// whereNull
DB::table('posts')->whereNull('deleted_at')->get();

3 - Joins

DB::table('posts')
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->select('posts.title', 'users.name as author')
    ->get();

4 - Insert, Update, Delete

// Insert
DB::table('posts')->insert(['title' => 'New Post', 'slug' => 'new-post']);

// Update
DB::table('posts')->where('id', 1)->update(['views' => DB::raw('views + 1')]);

// Delete
DB::table('posts')->where('published', false)->delete();

// Upsert
DB::table('posts')->upsert(
    ['slug' => 'hello', 'title' => 'Hello'],
    ['slug'],          // unique key
    ['title']          // columns to update on conflict
);