information overload

by sebastian de deyne

Eager load relations in Laravel using withWhereHas

5 Apr 2023

When using whereHas in Laravel, it’s not uncommon to also eager load the relation using with.

$posts = Post::query()
    ->with('author')
    ->whereHas('author', function (Builder $query) {
        $query->where('name', 'Seb');
    })
    ->get();

Laravel also has a more succinct method that combines the two: withWhereHas.

$posts = Post::query()
    ->withWhereHas('author', function (Builder $query) {
        $query->where('name', 'Seb');
    })
    ->get();

Information Overload newsletter

I occasionally send out a dispatch with personal stories, things I'm working on, and interesting links I come across.

Only for occasional updates. No tracking.