So i have codes that can search data based on relation columns,
there are 2 search input, 1 of them work really well but the other one doesn’t work.
my Model
Category
- id
- name
Task
- id
- title
- category_id
- company_id
Company
- id
- name
this is my blade:
<form action="/admin/manage" method="get">
<!--1. this is search name -->
<input name="search_name">
<!--2. this is company_id search -->
<select name="company_id" >
<option value="">Select All</option>
@foreach($companies as $company)
<option value="{{ $company->id }}" >{{ $company->name }}</option>
@endforeach
</select>
</form>
my controller:
if($request->search_name || $request->company_id){
$categories = Category::with(['tasks' => fn($query) => $query->where('title', 'like', '%' . $request->search_name . '%')])
->whereHas('tasks', fn ($query) =>
$query->where('title', 'like', '%' . $request->search_name . '%')
)->get();
}
else{
$categories = Category::with('tasks')->get();
}
this code seems unfinished, it is only search for title in my task and i don’t know how to add more code that can search 2 columns together
4
Answers
This is my own code, i added array inside where() parameter it works too,
You can try this to search from both of your values:
You can chain
where
so the query that is being generated will end up having aLIKE
AND
an=
criteria:Because you use Laravel 8, you can not use withWhereHas(). So you can define a function in your class and reuse it:
An then:
If you use Laravel 9 or above, you should use withWhereHas(). The method applies eager loading and check the condition at the same time. It makes your code shorter, cleaner and you don’t have duplicated codes.