How to Use get() Method in Laravel Eloquent
In Laravel Eloquent, use the
get() method to retrieve multiple records from the database as a collection. It executes the query and returns all matching rows, allowing you to work with the results easily.Syntax
The get() method is called on an Eloquent query builder instance to fetch all records that match the query conditions.
Basic syntax:
Model::query()->get();- retrieves all records.Model::where('column', 'value')->get();- retrieves filtered records.
php
use App\Models\User; $users = User::where('active', 1)->get();
Example
This example shows how to get all active users from the database using Eloquent's get() method. It returns a collection of user objects that you can loop through or manipulate.
php
<?php use App\Models\User; // Retrieve all users where 'active' column is 1 $activeUsers = User::where('active', 1)->get(); foreach ($activeUsers as $user) { echo $user->name . "\n"; }
Output
Alice
Bob
Charlie
Common Pitfalls
One common mistake is to forget calling get() and expecting the query to run immediately. Without get(), you only have a query builder instance, not the results.
Another pitfall is using get() when you expect a single record; in that case, use first() instead.
php
use App\Models\User; // Wrong: This does not execute the query $users = User::where('active', 1); // Right: This executes and fetches the results $users = User::where('active', 1)->get();
Quick Reference
| Method | Description |
|---|---|
| get() | Fetches all records matching the query as a collection |
| first() | Fetches the first record matching the query or null |
| all() | Fetches all records from the model's table |
| where() | Adds conditions to filter records before calling get() |
Key Takeaways
Use
get() to retrieve multiple records as a collection in Eloquent.Always call
get() to execute the query and fetch results.Use
where() before get() to filter records.For a single record, prefer
first() instead of get().The result of
get() is a collection you can loop through or manipulate.