📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework Eloquent ORM — Basics

Eloquent ORM — Basics

6 min read Quiz at the end
Use Eloquent's CRUD methods, query builder, aggregates, and findOrFail for database access.

Eloquent ORM Basics

// Model
class Post extends Model {
    protected $fillable = ["title", "body", "slug", "user_id"];
    protected $casts = [
        "published_at" => "datetime",
        "is_draft"     => "boolean",
    ];
}

// CRUD
$post = Post::create(["title" => "Hello", "body" => "World"]);
$post = Post::find(1);
$post = Post::findOrFail(1);  // 404 if missing
$post = Post::where("slug", "hello")->firstOrFail();

$post->update(["title" => "Updated"]);
$post->delete();

// Query builder
Post::where("is_draft", false)
    ->where("published_at", "<=", now())
    ->latest()
    ->take(5)
    ->get();

// Aggregates
Post::count();
Post::max("views");
Post::where("user_id", 1)->sum("views");
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which property lists mass-assignable fields?
💡 $fillable lists columns that can be mass-assigned via create() or fill().
2. What does findOrFail() do when record is missing?
💡 findOrFail() throws ModelNotFoundException if no record is found.
3. What does the $casts property do?
💡 $casts automatically converts column values to PHP types (JSON string to array etc.).
4. Which method saves a new record and returns the instance?
💡 Post::create($data) mass-assigns and saves, returning the new model instance.
5. What does latest() do?
💡 latest() adds ORDER BY created_at DESC.