Skip to main content
Category:

Eager Loading with Exact Columns in laravel


You can do Laravel Eager Loading and specify the exact columns you want to get from the relationship.


$users = App\Book::with('author:id,name')->get();


You can do that even in deeper, second level relationships:

 

$users = App\Book::with('author.country:id,name')->get();

 

Get All Fields Example:

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

Simple Select Example:

$posts = Post::with('comments:id,body')->get();

Select with statement Example:

$posts = Post::with(['comments' => function($query) {

return $query->select(['id', 'body']);

}])->get();

 

Multiple Relationships:

Sometimes you may need to eager load several different relationships in a single operation. To do so, just pass additional arguments to the with method:

$books = App\Models\Book::with(['author', 'publisher'])->get();

 

Nested Eager Loading

To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

$books = App\Models\Book::with('author.contacts')->get();

 

Nested Eager Loading morphTo Relationships

use Illuminate\Database\Eloquent\Relations\MorphTo;

$activities = ActivityFeed::query()
    ->with(['parentable' => function (MorphTo $morphTo) {
        $morphTo->morphWith([
            Event::class => ['calendar'],
            Photo::class => ['tags'],
            Post::class => ['author'],
        ]);
    }])->get();

 

if you want Always load some relationships when retrieving a model. To accomplish this, you may define a $with property on the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['author'];

    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Models\Author');
    }
}

 

If you would like to remove an item from the $with property for a single query, you may use the without method:

$books = App\Models\Book::without('author')->get();

 

if you want to specify additional query conditions for the eager loading query. Here's an example:

$users = App\Models\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');
}])->get();

In this example, Eloquent will only eager load posts where the post's title column contains the word first. You may call other query builder methods to further customize the eager loading operation:

$users = App\Models\User::with(['posts' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();

 

Example with MorphTo Relationships:

 

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;

$comments = Comment::with(['commentable' => function (MorphTo $morphTo) {
    $morphTo->constrain([
        Post::class => function (Builder $query) {
            $query->whereNull('hidden_at');
        },
        Video::class => function (Builder $query) {
            $query->where('type', 'educational');
        },
    ]);
}])->get();

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook