← Laravel tutorial

Laravel

Eloquent Models

Eloquent is Laravel's ORM: each model class maps to a database table, and Eloquent infers the table name and columns by convention rather than requiring you to spell them out manually.

Example: defining and querying a model

// app/Models/Post.php
class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

// Usage:
$latest = Post::orderBy('created_at', 'desc')->first();
echo $latest->title;

Post::orderBy(...)->first() reads almost like a sentence, and returns a real PHP object — no SQL string required anywhere in this code. $fillable is a safety list: only the fields named there can be mass-assigned from user input at once, which prevents a visitor from sneaking extra fields (like an is_admin flag) into a form submission that ends up saved to the database unexpectedly.

Example
// app/Models/Post.php
class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

// Usage:
$latest = Post::orderBy('created_at', 'desc')->first();
echo $latest->title;
Output
Prints the title of the most recently created post.