Patrick Simard
Patrick Simard

Reputation: 2375

Laravel 7 Query with() and using Where()

Hey guys I have a query that looks like this

$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table));

I need to filter the transaction based on the iso_id that belons to the current user logged in.

$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table))
->where('merchant.iso_id', '=', auth()->user()->isIso());

The iso_id I need to compare to, is inside the merchant table

auth()->user()->isIso() returns the correct iso_id if true or sends false if not

So my first try at this was to use where('merchant.iso_id', '=', auth()->user()->isIso())

But that returns that the column does not exist because for some reason, it's not switching from the transaction model to the merchant one.

I am not sure how to use the stuff inside with() as a selector for my where()

Any help would be appreciated!

Upvotes: 1

Views: 144

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

Try using whereHas to add the constraint:

$query = Transaction::with(['customer', 'batch'])
                    ->whereHas('merchant', function ($q) {
                         $q->where('iso_id', auth()->user()->isIso());
                    })
                    ->select(sprintf('%s.*', (new Transaction)->table))
                    ->get();

Upvotes: 1

Related Questions