Eager loading constraints

Submitted by stidges - 11 years ago

Ever find yourself wanting to only find models that have a certain relationship matching certain conditions? Laravel 4.1 makes this really easy, and introduces great eager loading constraints!

<?php

// Post model
class Post extends Eloquent {
    
    public function tags()
    {
        return $this->belongsToMany('Tag');
    }
}

// Tag model
class Tag extends Eloquent()
{
    
    public function posts()
    {
        return $this->belongsToMany('Post');
    }
}

// Imagine if you want to get ONLY the posts that have the tag 'laravel', that are posted
// in the last week.
$posts = Post::whereHas('tags', function($query)
{
    // Set the constraint on the tags
    $query->where('name', '=', 'laravel');
})->where('published_at', '>=', Carbon\Carbon::now()->subWeek())->get();