Skip to content
Advertisement

Laravel components with old() helper function

For my easy I have made a component which contains a dropdown in it. So that I can use it everywhere when I need it. This is the component

 <h5>{{$title}}</h5>

    <select class="select" {{$required_district}} name="{{$select_district}}" id="{{$select_district}}">

        <option value="" selected> {{ __('Select the district') }} </option>

        @foreach($districts as $district)
            <option value="{{ $district->id }}"
               {{ old($select_district) && $district->id == old($select_district)  ? 'selected' : '' }}>
                {{ $district->name_en }}</option>
        @endforeach

    </select>

    @error($select_district)
    <label class="text-danger" style="">{{$message}}</label>
    @enderror

What I do here is the title, input filed name id and other kinds of stuff make dynamically via @slot() like below

    @component('destrict')

 @slot('title')
 Where do you want a job to be started
 @endslot

 @slot('select_district')
 selected_district
 @endslot

 @slot('required_district')
 required
 @endslot

    @endcomponent

Ok things work well but when I submit the form which contains this component when the validation gets fails then it generates the below error.

array_key_exists(): The first argument should be either a string or an integer

The problem occurs with this line when form redirect back with validation errors

 {{ old($select_district) && $district->id == old($select_district)  ? 'selected' : '' }}

If I remove the {{ old($select_district) }} or if I just use it like {{ old('name_here') }} then things working as they should be. But since I need to use this component inside more pages I would like to fix this issue . So could anyone please help me to fix this.

Advertisement

Answer

This may be tricky but I was able to fix the error like below

old(''.$select_district.'')

Thanks

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement