Laravel Eager Loading with method example

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.


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();