Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Laravel Eloquent Models
Laravel Advanced FREE

Eloquent Models

Lesson 1 of 17 Advanced Interactive

Eloquent is Laravel's ORM. Each model maps to a database table.

Conventions

  • Model: Post -> table: posts
  • Primary key: id (default)
  • Timestamps: created_at, updated_at

Fillable & Casts

$fillable for mass assignment. $casts for type casting.

Syntax

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

Post::create($request->validated());
Post::where("status", "published")->get();
Eloquent Basics
PHP
<?php
use App\Models\Post;

// Select
$posts = Post::where("published", true)
    ->orderBy("created_at", "desc")
    ->limit(10)
    ->get();

// Find by ID
$post = Post::find(1);

// Insert
Post::create([
    "title" => "New Post",
    "body" => "Content here",
]);

// Update
$post = Post::find(1);
$post->title = "Updated";
$post->save();

// Mass update
Post::where("draft", true)->update(["published" => true]);

// Delete
Post::destroy(1);

// Aggregates
$count = Post::count();
$latest = Post::latest()->first();

Practice

1
Exercise

Create a User model with fillable and a cast.

Answer
class User extends Model {
    protected $fillable = ["name", "email"];
    protected $casts = ["email_verified_at" => "datetime"];
}

Quick Quiz

1

What does $fillable protect against?

$fillable controls which fields can be mass-assigned.

Interview Questions

Filling multiple model attributes at once via create() or fill(). $fillable whitelists safe attributes.