Home > Enterprise >  Filter using wildcard for relationships
Filter using wildcard for relationships

Time:08-28

I have a input using a datalist where it's possible to either type in the name of the car part type or use a dropdown. Looks like this

  <input value="{{ request()->input('part-type') }}" list="part-type-list"
                                   name="part-type" >
                            <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);
   }

CodePudding user response:

there is two problems in your code

  • $request->input('part-type') can not be used in quotations
  • you must use whereHas 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.

  • Related