Search code examples
javascriptlaraveleloquentvoyager

How to add a Condition to laravel voyager relationship BelongsToMany


I need to get variants where parent_id is null in Belongs To Many Relation in Laravel Voyager

relation.blade.php

<select
    class="form-control @if(isset($options->taggable) && $options->taggable == 'on') select2-taggable @else select2-ajax @endif"
    name="{{ $relationshipField }}[]" multiple
    data-get-items-route="{{route('voyager.' . $dataType->slug.'.relation')}}" data-get-items-field="{{$row->field}}"
    @if(isset($options->taggable) && $options->taggable == 'on')
    data-route="{{ route('voyager.'.\Illuminate\Support\Str::slug($options->table).'.store') }}"
    data-label="{{$options->label}}"
    data-error-message="{{__('voyager::bread.error_tagging')}}"
    @endif
    >

Solution

  • You will need to customise the controller called by the route : {{route('voyager.' . $dataType->slug.'.relation')}} which will be $breadController.'@relation'. You can in the said controller override the public method relation by inspiring you on the original one (l.822) to send back the eloquent models it normally would filtered by a ->where('parent_id', null) (in both l.838 and l.840).

    You might also be interested in looking into the Query Scope offered by Laravel.