DEV Community

Morcos Gad
Morcos Gad

Posted on

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.

<?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);
    }
}
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.

Top comments (0)