I have an input using a datalist where it's possible to either type in the name of the car part type or uses a dropdown. Looks like this
<input value="{{ request()->input('part-type') }}" list="part-type-list"
name="part-type" class="form-select">
<datalist id="part-type-list">
@foreach($partTypes as $partType)
<option @if(request()->input('plaintext') == $partType->name) selected
@endif value="{{$partType->name }}">{{ $partType->name }}
</option>
@endforeach
</datalist>
The $partTypes
are coming from a query CarPartType::all()
and it's used to show the values you can filter car parts by.
In my controller, I am trying to see if I have a part-type filter and then changing the query to filter out the ones that don't match it. The problem is that I don't have the name of the car part types on the car parts table but only the id. Here is an example of me trying to query it through the relationship but it does not work.
$parts = CarPart::query();
if($request->filled('part-type')) {
$parts = $parts->where('carPartType.name', 'like', "% $request->input('part-type')%");
return $parts->get();
}
The relationship I am trying to use
public function carPartType(): BelongsTo
{
return $this->belongsTo(CarPartType::class);
}
there is two problems in your code
$request->input('part-type')
can not be used in quotationswhereHas
to make relationship constraints.if ($request->filled('part-type')) {
$value = $request->input('part-type');
$parts = $parts->whereHas('carPartType', function ($query) use ($value) {
return $query->where('name', 'like', "%$value%");
});
return $parts->get();
}
I hope this works for you.