Isn't location singular? No s. And an array
if (count($request->location)) {
$ids = $request->location;
$query = $query->whereHas('locations', function($q) use ($ids) {
$q->whereIn('location_id', $ids);
});
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all,
I am trying to filter the output of a certain model for my blade view. Meaning, in my Controller I do the following:
$query = Company::query();
if ($request->locations != null){
$id = $request->locations;
$query = $query->whereHas('locations', function($q) use ($id) {
$q->where('location_id', '=', $id);
});
}
elseif ($request->locationMandatory != null) {
$query = $query->has('locations');
}
if ($request->scopes != null){
$id = $request->scopes;
$query = $query->whereHas('scopes', function($q) use ($id) {
$q->where('scope_id', '=', $id);
});
}
elseif ($request->scopeMandatory != null) {
$query = $query->has('scopes');
}
$companies = $query->get();
In my frontend I just do @foreach to list all the "$companies" I try to filter.
Basically, that works, though the Controller is not able to process multiple filter elements in 1 variable. E.g. if I want to filter for multiple "locations" the Controller only takes the last location-id that he is given.
The filter logic in the frontend looks as follows:
<form action="{{ route('...') }}" method="post">
@csrf
...
<select name="location[]" multiple="multiple" class="form-control filterselect @error('location') is-invalid @enderror" id="location" style="width: 100%">
@foreach ($locations as $location)
<option value="{{ $location->id }}">{{ $location->name }}<option>
@endforeach
</select>
...
Submit
</form>
Anyone can help me with this?
Thanks acrm
add the table name
if (count($request->location)){
$query = $query->whereHas('locations', function($q) use ($request) {
$q->whereIn('locations.id', $request->location);
});
}
Please or to participate in this conversation.