Laravel Eager Loading with method example

Posted on

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 AppModels;

use IlluminateDatabaseEloquentModel;

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

Exit fullscreen mode

Now we get data in controller.

$posts = Post::all();

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

Exit fullscreen mode

In eager loading, all the users are also retrived with post records – with()

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

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

Exit fullscreen mode

multiple relationships

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

Exit fullscreen mode

Nested Eager Loading

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

Exit fullscreen mode

specific columns

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

Exit fullscreen mode

I hope everyone enjoys the code.

Leave a Reply

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