Query builder
| DB::table | |
| Where clauses | |
| Order and limit | |
| First and find |
DB::table
The query builder talks to tables directly, with no model class in between. The table method names the table, and get runs the query and returns the rows.
Each row arrives as a plain object with one property per column. Loop over the result exactly like an array.
use Illuminate\Support\Facades\DB; $posts = DB::table("posts")->get(); foreach ($posts as $post) { echo $post->title; }
Where clauses
The where method adds one filter per call, and chained calls combine with AND logic. Three arguments set the column, the operator, and the value.
Two arguments are shorthand for equality. Use the three-argument form for greater-than, less-than, and other comparisons.
$posts = DB::table("posts") ->where("status", "published") ->where("views", ">", 100) ->get();
Order and limit
The orderBy method sorts rows by a column, newest or oldest first. The limit method caps how many rows come back, which keeps pages fast.
$posts = DB::table("posts") ->orderBy("id", "desc") ->limit(10) ->get();
First and find
The first method returns the top matching row or null when nothing matches. The find method is the shortcut for looking up one row by id.
$post = DB::table("posts")->where("id", 1)->first(); $same = DB::table("posts")->find(1);
Next: Seeders and factories
Article author: Arthur Isaev