Querying with where
Eloquent builds queries using chainable methods. Start with where to filter results:
$users = User::where('active', true)->get();
Chain multiple conditions together:
$users = User::where('active', true)
->where('age', '>=', 18)
->get();
Try it Yourself →
orWhere and whereIn
Use orWhere when you need an OR condition, and whereIn for matching against a list:
$users = User::where('status', 'active')
->orWhere('status', 'pending')
->get();
$users = User::whereIn('id', [1, 2, 3])->get();
Ordering and Limiting
Sort results with orderBy and limit them with take or limit:
$users = User::orderBy('name', 'asc')->take(10)->get();
$latest = User::orderBy('created_at', 'desc')->first();
Aggregates: sum, avg, count
Eloquent makes it easy to run aggregate queries without writing SQL functions:
$totalUsers = User::count();
$averageAge = User::avg('age');
$totalBalance = Account::sum('balance');
You can also use pluck to get a single column's values:
$emails = User::pluck('email');
$names = User::where('active', true)->pluck('name');
Query Scopes
Scopes let you encapsulate common queries into reusable methods. Define a scope in your model:
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', true);
}
}
Then use it in your queries:
$activeUsers = User::active()->get();
Collections
Eloquent queries return Collection objects. Collections have dozens of useful methods for working with data in memory:
$users = User::all();
$names = $users->map(function ($user) {
return $user->name;
});
$active = $users->filter(function ($user) {
return $user->active;
});
Collections make data manipulation clean and chainable.