Topics Eloquent ORM Advanced Eloquent Techniques
advanced 16 min read

Advanced Eloquent Techniques

Subquery selects, lazy loading prevention, strict mode, and performance optimization in Laravel 13.

Subquery Selects

use App\Models\User;
use App\Models\Post;

// Add a subquery select
$users = User::select("users.*")
->selectSub(
Post::whereColumn("user_id", "users.id")
->selectRaw("count(*)"),
"posts_count"
)
->get();

// Order by subquery
$users = User::orderByDesc(
Post::whereColumn("user_id", "users.id")
->selectRaw("count(*)")
)->get();

Lazy Loading Prevention

// In AppServiceProvider
use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());
Model::preventAccessingMissingAttributes(! $this->app->isProduction());
}

Cursors & Chunks

// Chunk for memory-efficient processing
User::chunk(100, function (Collection $users): void {
foreach ($users as $user) {
// Process each user
}
});

// Cursor for lazy collections
foreach (User::cursor() as $user) {
// Only one model in memory at a time
}

// Lazy collection
User::lazy(100)->each->doSomething();

Examples

<?php
use App\Models\User;

// Get users with their latest post title via subquery
\$users = User::select('users.*')
    ->selectSub(
        \DB::table('posts')
            ->whereColumn('user_id', 'users.id')
            ->orderByDesc('created_at')
            ->limit(1)
            ->select('title'),
        'latest_post_title'
    )
    ->get();

echo \$users->first()?->latest_post_title;

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.