3

I have created a table as follows:

Table 'adjustment' consists of columns: id, adjustment_number, status.

The adjustment table has a relationship called materialloc, and another relationship to sbin.

Then, I crafted a query program like this using Laravel 10.

$query = Adjustment::with('materialloc.sbin'); if ($request->has('search') && $request->input('search')) { $searchTerm = $request->input('search'); $query->whereHas('materialloc.sbin', function ($query) use ($searchTerm) { $query->where('name', 'like', '%' . $searchTerm . '%'); }); $query->orWhere('adjustment_number', 'like', '%' . $searchTerm . '%'); } 

Why doesn't the search using adjustment_number work? However, when I search by name in materialloc.sbin, it works.

Is there something wrong with my use of whereHas, where, or orWhere?

1 Answer 1

2

You need to merge whereHas and orWhere into a common search:

$query = Adjustment::with('materialloc.sbin'); if ($request->has('search') && $request->input('search')) { $searchTerm = $request->input('search'); $query->where(function ($q) use ($searchTerm) { $q->whereHas('materialloc.sbin', function ($query) use ($searchTerm) { $query->where('name', 'like', '%' . $searchTerm . '%'); }); $q->orWhere('adjustment_number', 'like', '%' . $searchTerm . '%'); }); } 

Similar themed questions:

In the referred Eloquent Relationships from Laravel Docs, it is well illustrated that you enclose this condition within parentheses in a common where clause. While without it (as you did), there is no parentheses, which can lead to different query behavior than expected.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.