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.
Eloquent is Laravel's ORM. Each model maps to a database table.
Post -> table: postsid (default)created_at, updated_at$fillable for mass assignment. $casts for type casting.
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();
<?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();
Create a User model with fillable and a cast.
class User extends Model {
protected $fillable = ["name", "email"];
protected $casts = ["email_verified_at" => "datetime"];
}
What does $fillable protect against?
$fillable controls which fields can be mass-assigned.
Filling multiple model attributes at once via create() or fill(). $fillable whitelists safe attributes.