Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cataract0523's avatar

How can I filter by relationship?

I have a model called Company which may have many Vacancy models. And this Vacancy has one PipeVacancy. So my question is how can I filter the query to bring me only the Vacancies that already have a PipeVacancy. I was think maybe I could achieve this with scoped queries but I had no idea how to write that piece of code. What I want with this is to avoid that inner @if.

                 @foreach($company->vacancies as $vacancy)
                                    @if($vacancy->pipeVacancy)
                                        <li>
                                            <div class="row">
                                                <div class="col-md-8">
                                                    {{$vacancy->title}}
                                                </div>
                                                <div class="col-md-4">
                                                    <a href="{{route('myroute',$vacancy->id)}}">
                                                        <button class="btn btn-sm btn-success"
                                                                type="button">{{__('labels.Apply')}}
                                                        </button>
                                                    </a>
                                                </div>
                                            </div>
                                        </li>
                                    @endif
                                @endforeach

Any tips?

0 likes
1 reply
realrandyallen's avatar

Try something like this:

$company = Company::has('vacancies.pipeVacancy')->get();

of course you can add any where statements you need to to filter down to a specific company

Please or to participate in this conversation.