I am a beginner in laravel, in my form, there is a table and some lookup fields like text input, which I want to search the values in and display on the table.
When I perform a search process on a text input like name, filtering the table after enter works fineŘ but when I add a number of search fields, like filtering on name and city, it no longer filters on any of the name or city fields. can’t In fact, the request value in the controller returns an empty value.
Briefly,in indexfiltering.blade.php:
...
<div>
<a href="{{ route('customers.indexfiltering')}}">search</a>
</div>
...
<div>
<input type="text" class="form-control" id="name" name="name" value="{{ $name }}">
</div>
<div>
<input type="text" class="form-control" id="city" name="city" value="{{ $city }}">
</div>
and in my controller:
public function indexFiltering(Request $request)
{
$name= $request->query('name');
$city= $request->query('city');
if (!empty($name) || !empty($city)) {
$customer= Customer::sortable()
->where('customer.name', 'like', '%'.$name.'%')
->where('customer.city', $city)
->paginate(8);
} else {
$customers = customer::sortable()
->paginate(8);
}
return view('customers.indexfiltering',
compact('customer'))
->with('customers', $customers)
->with('name', $name)
->with('city', $city);
}
The second problem is that I want filtering to be done by selecting any item from the html select. Currently this is not done and selecting any option has no effect on filtering
4
Answers
You might need to start a query in the begining of the function like $query = Customer::query(); and check requests after.
As my comment stated you are searching by name AND city always, never individually (due to your if statement).
You could change your code to below:
name
if name is not emtpy.city
if city is not empty.name
andcity
are both not empty.You need to modify the query to dynamically add conditions based on whether the input is set and not empty.
here is a slightly cleaner option using the when() that allows to remove conditionals: