Laravel ORM Eloquent is brilliant!

That being said, let’s try to tackle very common questions that appear when you try to get related models loaded.

Want to skip the preface and get Straight to The Point?

Why don’t we create a popular category-post relation in not less popular MySQL db ?

So here we go!


What we have here is simple ONE-TO-MANY relation that we can handle without any additional pivot tables.

Here are the tables:


Of course we don’t want to run SQL queries ourselves, so for the artisans, a migration files :)





Next let’s setup our relations:






Seed the database …


Now, say you want to get all the categories and all the related posts without unwanted redundant queries – all we have to do is eager load relation:


Now, something harder, what I’m asked about pretty often. Let’s get all the categories and their related posts, but  limited in any way:



And last but not least! Now you may want only those categories, that have posts again with title like ‘%st’



As simple as that!

And for all those collections we needed only 2 queries to the database. Impressive isn’t it?

Be sure to check other features and leave a comment with any questions.

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

Tweaking Eloquent relations – how to get lat... Have you ever needed to show only single related model from the hasMany relationship on a set of parents? Being it latest, highest or just rand...
Querying relations in Laravel 4: nested relation Previously we dealt with simple relations defined in Eloquent models and eager loading them in order to save database queries. Now imagine nest...
Querying relations in Laravel: get Models where la... Another part of Querying relations in Laravel will cover such problem: I want to get SomeModels that have latest RelatedModel (hasMany) matchin...
Laravel – querying any level far relations w... Eloquent provides one Relation type for far related tables - hasManyThrough. However it works only with with cascade of hasOne/hasMany relations a...