Laravel Eloquent Queries with Eager Loading

  1974 views   7 months ago Laravel

When you make relationship in Laravel eloquent relationship, there are two ways you can access eloquent relationships data. In a lazy loading, when you access the property, then relationships data loaded.

For example, Post model is belongs to User model. So when you want to get all users data with posts records. Here is Post model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the users that write article
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Now we get data in controller.

use App\Models\Post;

$posts = Post::all();

foreach ($posts as $post) {
    echo $post->user->name;
}

In the above example, all posts data will loop and retrieve user for the post. What if there are hundreds of posts? All will loop and retrive user for the post in all loop.

In eager loading, all the users are also retrived with post records.

$posts = Post::with('user')->get();

foreach ($posts as $post) {
    echo $post->user->name;
}

This way, eager loading is better than lazy loading to retrive data in one time. Now lets look mode example for eager loading.

If you have multiple relationships with single model, you can retrive all relationships records with eager loading.

$posts = Post::with(['user', 'category'])->get();

Nested Eager Loading

If you have nested Eager Loading, you may retrive as below:

$posts = Post::with('user.address')->get();

If you only want to retrive specific columns in Eager Loading, pass id and any other foreign key columns which you want to retrive with records.

$posts = Post::with('user:id,email,phone,post_id')->get();

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]