Query builder

Contents
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

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: