Q:

Laravel Eloquent "with" return relations with limit

I have simple Laravel relations between Category and Article models. I need to return the list of all categories with related articles.       
Test data: 3 categories and 15 articles (5 articles per category).
Expected result: collection of all categories with 2 latest related articles for each category
By default case I should use something like:
Category::with('articles')->get();

It's ok - I got 3 categories. Each category has "relations" with 5 related records.
Next, I tried:
Category::with(['articles' => function ($query) {
    $query->orderBy('created_at', 'desc');
    $query->limit(2);
}])->get();

But this is the wrong way. This construction in "raw" query looks like:  
select * from `articles` where `articles`.`category_id` in (select id from categories) limit 2

So it's returned me a wrong result as expected...
I need all categories and latest 2 articles for each category (3 * 2 = 6 records) this query returned just 2 records

A:

There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class Category extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Article extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then you can apply ->limit(2) to your relationship.

