PHP

Eager Load Relationships with Constraints and Specific Columns

Optimize performance by eager loading only necessary columns or applying custom `WHERE` clauses to your Eloquent relationships to fetch specific related data efficiently.

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Example Usage: Eager load only specific columns of a relationship
$usersWithPostTitles = User::with('posts:id,title,user_id')->get();
// Access: $user->posts->first()->title;

// Example Usage: Eager load with constraints on the relationship query
$usersWithApprovedComments = User::with(['comments' => function ($query) {
    $query->where('approved', true)->orderBy('created_at', 'desc');
}])->get();
// Access: $user->comments->first()->body;

// Example Usage: Eager load multiple relationships with specific columns and constraints
$posts = Post::with([
    'user:id,name,email',
    'comments' => function ($query) {
        $query->where('is_spam', false);
    }
])->find(1);
// Access: $posts->user->name, $posts->comments->first()->body;
How it works: Eager loading with constraints allows you to fetch related models based on specific conditions, reducing the amount of data loaded. By passing a closure to the `with` method, you can add `where` clauses, `orderBy`, or other query builder methods to the relationship query. Additionally, you can specify which columns to select from the related table using a colon-separated string (`'relation:id,name'`), further optimizing performance by only retrieving necessary data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs