Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

userr3333's avatar

Macro for whereExists($subQuery)?

Anyone has an Eloquent macro that has been used extensively without issues?

Basically I want to be able to use whereExists by passing a subquery instead of having to use whereId.

User::where('name', 'me')->whereExists(
	User::whereNull('column')
)
0 likes
3 replies
mike_isp's avatar

Is it always the same subquery? Would a model scope be enough?

userr3333's avatar

@mike_isp no, it's huge and complex distinct subqueries. Also I forgot to add that would like to avoid using the closure method since I had issues in the past. Using raw methods is very ugly too.

amitsolanki24_'s avatar

@userr3333

use Illuminate\Database\Query\Builder;


Builder::macro('whereExist', function ($query, $column_name) {
            return $query->whereNull($column_name);
        });

Please or to participate in this conversation.