/    Sign up×
Bounties /Pin to ProfileBookmark

How is eager loading achieved in Laravel and what are the benefits?

+ 1,000
Copy linkTweet thisAlerts:
Aug 11.2022

Specifically, what’s the difference between has and with?

to post a answer
Laravel

1 Replies

Copy linkTweet thisAlerts:
@deemoSep 01.2022 — The difference between the has() and with() methods is that, has() simply checks if a relationship exists between 2 models whereas with() is used to eager-load the related eloquent model.
// has - This will return all posts that have at least 1 comment

$posts = Post::query()
->has('comments')
->get();

// with - This will eager-load the comments and reduce the amount of queries

Post::with('comments')->get();


A benefit of eager-loading is simply reducing the amount of queries to return the parent model along with the relation model.

https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
×

Success!

Help @TyGar spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.4,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...