Skip to content
Saidur Rahman

PHP & Frameworks

5 Hidden Laravel Eloquent Features Every Developer Forgets Exist

Most Laravel developers rely on basic hasMany and belongsTo relations, but Eloquent includes powerful built-in tools that eliminate boilerplate code and prevent silent SQL bugs. Here are 5 native Eloquent features you should start using today.

· 2 min read

Most Laravel devs rely heavily on basic hasMany and belongsTo relationships. But Eloquent has built-in features designed to eliminate boilerplate code and kill silent SQL bugs—yet they barely get used.
Here are 5 hidden features you should start using today:

1. latestOfMany() & oldestOfMany()

Stop fetching all related models to pluck the latest one in PHP. Define a single-record subquery directly in your relationship:
PHP

public function latestOrder(): HasOne
{
    return $this->hasOne(Order::class)->latestOfMany();
}

⚡ Benefit: Generates a single, highly optimized SQL query under the hood.

2. withDefault()

Tired of seeing "Attempt to read property on null" when an optional relation doesn't exist? Stop cluttering views with optional() or ??.
PHP

public function author(): BelongsTo
{
    return $this->belongsTo(User::class)->withDefault([
        'name' => 'Guest Author',
    ]);
}

⚡ Benefit: Automatically hydrates a dummy model if the relation is missing.

3. Relationship Chaperoning (chaperone())

When creating a child record through a parent model, Laravel usually makes a fresh DB call if you try to access $child->parent.
PHP

public function comments(): HasMany
{
    return $this->hasMany(Comment::class)->chaperone();
}

⚡ Benefit: Binds the parent object already in memory to the child, saving an extra SQL query.

4. Custom Pivot Models via using()

If your belongsToMany pivot table contains extra logic, custom methods, or dates, stop treating it like a plain array. Extends Pivot and attach it:
PHP

public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class)
                ->using(TeamUser::class)
                ->withPivot('expires_at');
}

⚡ Benefit: Turn $user->pivot into a fully functional Eloquent model instance with custom methods.

5. whereHas() Filtering

Stop pulling large datasets into memory to filter them with Collections. Filter directly at the database level:
PHP

// Retrieve only posts with non-spam comments
$posts = Post::whereHas('comments', function ($query) {
    $query->where('is_spam', false);
})->get();

⚡ Benefit: Drastically reduces memory footprint and speeds up request times.

Share