Retrieving Models

Retrieving Models and Eloquent Collections

Every query-builder method of The Query Builder works on a model, and get() or all() returns an Eloquent Collection of hydrated models instead of stdClass rows:

Querying products and working with the collectionSQL
use App\Models\Product;
$books = Product::where('category_id', '<=', 4)->orderByDesc('price')->limit(3)->get();
echo get_class($books), ' of ', $books->count(), "\n";
echo json_encode([$books->modelKeys(), $books->sum('price')]), "\n";
Output
-- select * from `products` where `category_id` <= 4 and `products`.`deleted_at` is null order
by `price` desc limit 3
Illuminate\Database\Eloquent\Collection of 3
[[4,2,6],135.5]

The deleted_at clause is the soft-delete scope of Deleting and Pruning, and sum() ran in PHP over the loaded models. The Eloquent collection adds model-aware methods to the base one: modelKeys(), fresh(), load() (Lazy Eager Loading) and toQuery(), which turns the set back into a whereIn query. For big tables, chunkById(), lazy() and cursor() stream models as in Chunking and Cursors. The classic mistake is Product::all()->where(...), which loads every row to filter in PHP what MySQL 524 could have filtered.