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

eaglehdr's avatar

Build Search query by reference ID in a table

I might be using wrong terminology/words here.

I have 2 tables

Orders

| id |     order_id     | customer_id|
|  1 |    RD34234234    |     3      |
|  2 |    CF43345376    |     4      | 

Payments

| id | order_id |         pay_id         |
|  1 |     1    |   pi_jkfshjk32948sdf   |
|  2 |     2    |   pi_234lkj3483898ad   |

I have a relationship between them so in my admin panel.. I have a Payments page where I am looping payments and getting order data by $payment->order->order_id .

The issue that now I want to do search.. currently I am using livewire for search and in livewire I have

$this->payments = Payment::where('pay_id', 'LIKE', "%".$this->searchString."%")

this fetches specific payment by pay id.. now my client want to search using order_id (which is RD23723489' from order table) but I am unable to build a query .. i even tried $this->payment = Payment::with('orders')->where('order_id', xxxxxxx)` but still not getting data. (note: markdown is not working so I had to improvise)

0 likes
6 replies
Sinnbeck's avatar

You can use where has. it limits the payments, by the relationship.

$this->payments = Payment::whereHas('orders', function($query) use ($orderId) {
    $query->where('order_id', $orderId);
})->get();
1 like
wfajriansyahh's avatar

@Sinnbeck im sorry, i want to ask, this will trigger if $orderId is null / empty? i think we can use when for avoid that. he wanted to search with wire model input.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@wfajriansyahh So if its null it should show all?

$this->payments = Payment::when($this->order_id, function($query, $orderId) {
    $query->whereHas('orders', function($query) use ($orderId) {
         $query->where('order_id', $orderId);
      });
->get();
1 like
wfajriansyahh's avatar

@Sinnbeck yes, if null will show all, and if wire:model $orderId changed, will search by $orderId in model Payment with relationship orders and search order_id

eaglehdr's avatar

@wfajriansyahh well in my case, its a search query variable ($this->order_id). I am using livewire so either my variable has something or it is null. so if it has something, it searches. if its null then returns all records

Please or to participate in this conversation.