Laravel Eloquent ORM


In the ever-evolving world of web development, Laravel Eloquent ORM stands tall as a trusted companion for developers. It’s not just about basic CRUD operations; Eloquent is a powerhouse of advanced features that can make your development journey smoother, efficient, and downright enjoyable. So, grab a cup of your favorite beverage, because we’re about to dive into the world of advanced Eloquent relationships in Laravel!

Benefits of Laravel Eloquent ORM

Laravel’s Eloquent ORM streamlines database interactions, enhances code readability, and accelerates development, making it a valuable asset for developers building web applications. So, its rich feature set and developer-friendly approach contribute to its popularity in the PHP framework landscape.

Eager Load Relationships with “with”

Let’s start with the basics. The `with()` method is your ticket to efficient database queries. Imagine this: You have a user model, and you want to fetch users along with their posts and comments. Instead of making separate queries for users, posts, and comments (and falling into the dreaded N+1 query trap), you can do this:

$users = User::with('posts.comments')->get();

Boom! You’ve just saved precious milliseconds.

Filter Based on Related Records Existence Using “has”

The `has()` method is your go-to for filtering records based on related records’ existence. For instance, you want to find users who have at least one post. Here’s the magic incantation:

$usersWithPosts = User::has('posts')->get();

With a single line of code, you’ve filtered users like a pro.

Combine “with” and “whereHas” with “withWhereHas”

But what if you want to mix eager loading with relationship existence checks? Enter `withWhereHas()`. It’s like having your cake and eating it too. Here, we’re loading users and their posts where the posts are published:

$usersWithPublishedPosts = User::withWhereHas('posts', function ($query) {

$query->where('published', true);


Efficiency and precision in one shot!

Apply Nested Relationship Constraints with “whereRelation”

Want to dive deeper? `whereRelation()` lets you apply constraints to nested relationships. Say you’re looking for users with comments from a specific author within their posts:

$usersWithCommentsFromAuthor = User::whereRelation('posts.comments', 'author_id', 1)->get();

Nested queries, handled like a champ!

Match Any Related Records Using “orWhereHas”

Sometimes, you need to find records with related data meeting one of several conditions. So, enter `orWhereHas()`. It’s like building complex queries with LEGO blocks:

$usersWithPostsInCategories = User::where(function ($query) {

    $query->orWhereHas('posts', function ($query) {

        $query->where('category_id', 1);

    })->orWhereHas('posts', function ($query) {

        $query->where('category_id', 2);



Effortlessly switch between conditions.

Find Models Without Related Records Using “doesntHave”

The `doesntHave()` method comes to the rescue when you want to find models without any related records. Imagine finding customers without any orders:

$customersWithoutOrders = Customer::doesntHave('orders')->get();

No orders? No problem!

Discover Models Without Specific Relationship Conditions Using “whereDoesntHave”

When you need to get even more granular, `whereDoesntHave()` helps you filter records without related records satisfying specific conditions. For instance, customers without unpaid orders:

$customersWithoutUnpaidOrders = Customer::whereDoesntHave('orders', function ($query) {

    $query->where('paid', false);


Unpaid bills? Unlikely.

Retrieve Relationship Sums Using “withSum”

Want to do some math? `withSum()` is your arithmetic buddy. Fetch the sum of values in related records effortlessly. Then, imagine you want to load posts with the sum of likes on their comments:

$postsWithCommentLikesSum = Post::withSum('comments', 'likes')->get();

Adding up the likes, piece of cake!

Check If Related Records Exist Using “withExists”

Curious if related records exist? `withExists()` lets you know. Let’s imagine checking if users have any unread messages:

$usersWithUnreadMessages = User::withExists('messages')->get();

Unread messages? You’re in the know!

Get Relationship Counts Using “withCount”

Lastly, `withCount()` is your ticket to fetching the count of related records without actually loading them. For instance, load posts along with the count of comments:

$postsWithCommentCounts = Post::withCount('comments')->get();

Counting made simple!

Conclusion – Laravel Eloquent ORM

There you have it, a whirlwind tour of advanced Eloquent ORM in Laravel! These tips are your secret sauce for building efficient, expressive, and powerful queries. So, embrace the magic of Eloquent, level up your Laravel game, and make your code shine.

Remember, the Laravel ecosystem is vast, and there’s always more to explore. So, Keep coding, keep learning, and keep building amazing things. Happy coding, my fellow Laravel artisans!

Leave a Reply

Your email address will not be published. Required fields are marked *