tylernathanreed's avatar

Joining Eloquent Relations

I use joins quite a lot, and it's often frustrating to me that Eloquent doesn't allow me to join over relationships. This leads to me joining over relationships in a repetitive manner, when really I should be leveraging Eloquent for my joins.

My frustration ultimately led me towards creating a package (reedware/laravel-relation-joins) to solve this problem, so I figured I'd share it with you guys.

With this package, instead of doing this:

User::query()
    ->join('posts', function ($join) {
        $join->on('posts.user_id', '=', 'users.id');
        $join->whereNull('posts.deleted_at');
    });
    ->join('comments', function ($join) {
        $join->on('comments.post_id', '=', 'posts.id');
        $join->where('comments.likes', '>=', 10);
        $join->whereNull('comments.deleted_at');
    });

You can do this:

User::query()->joinRelation('posts.comments', [
    $join->where('comments.likes', '>=', '10');
});

This package supports aliases, circular references, and a whole lot more. Hopefully you like it!

0 likes
0 replies

Please or to participate in this conversation.