0
0
LaravelHow-ToBeginner · 3 min read

How to Use all() Method in Laravel Eloquent

In Laravel Eloquent, use the all() method on a model to retrieve all records from its corresponding database table as a collection. For example, User::all() fetches all users from the users table.
📐

Syntax

The all() method is called statically on an Eloquent model class. It returns a collection of all records from the model's database table.

  • Model::all(): Fetches all rows from the table linked to Model.
  • Returns an Illuminate\Database\Eloquent\Collection containing model instances.
php
Model::all();
💻

Example

This example shows how to get all users from the database using the all() method and loop through them to display their names.

php
<?php
use App\Models\User;

$users = User::all();

foreach ($users as $user) {
    echo $user->name . "\n";
}
Output
Alice Bob Charlie
⚠️

Common Pitfalls

Common mistakes when using all() include:

  • Using all() on a query builder instance instead of the model class, which causes errors.
  • Fetching all records when the table is very large, leading to performance issues.
  • Expecting all() to accept conditions or filters (it does not).

Use where() or other query methods before get() for filtered results.

php
<?php
// Wrong: calling all() on a query builder instance
$users = User::where('active', 1)->all(); // Error

// Right: use get() after where()
$users = User::where('active', 1)->get();
📊

Quick Reference

MethodDescription
Model::all()Retrieve all records from the model's table as a collection.
Model::where(...)->get()Retrieve filtered records with conditions.
Model::find(id)Retrieve a single record by primary key.
Model::paginate(n)Retrieve records with pagination.

Key Takeaways

Use Model::all() to get all records from a table as a collection.
all() does not accept filters; use where() with get() for conditions.
Avoid using all() on large tables to prevent performance issues.
Always call all() statically on the model class, not on query builder instances.