Laravel Livewire – Multi select input data is lost after selection

  jquery-select2, laravel, laravel-livewire, php

i’m having a Clinic(id,name,&services from service class on it ) and when i need to store my services on database it saved normally but with an empty array without my services data
here is my view

<form class="form-horizontal" wire:submit.prevent="storeClinic">
    <div class="form-group">
        <label class="col-md-4 control-label">اسم العيادة</label>
            <div class="col-md-4">
                <input type="text" placeholder="اسم العيادة" id="name" name="name" class="form-control input-md" wire:model="name"/>
            </div>
    </div>
    <div class="form-group">
        <label class="col-md-4 control-label">اختارالخدمات</label><br/>
        <div class="col-md-4" wire:ignore>
            <select class="selectServices form-control input-md" id="selectServices" multiple wire:model.lazy="c_services">
                @foreach($services as $service)
                    <option value="{{$service->id}}">{{$service->name}}</option>
                @endforeach
            </select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-4 control-label"></label>
        <div class="col-md-4">
            <button type="submit" class="btn btn-success">اضافة</button>
        </div>
    </div>
</form>

, my script

@push('scripts')
<script>
    $(document).ready(function(){
        $('.selectServices').select2();
        $('.selectServices').on('change',function(e){
            var data = $('.selectServices').seleect2("val");
            @this.set('c_services',data);
        });
        window.livewire.on('clinicStore', () => {
            $('.selectServices').select2();
        });
    });
</script>

@endpush

, my component

public $name;
public $c_services = [];
use WithPagination;
public function storeClinic(){
    $input = [
        'name' => $this->name,
        'c_services' => json_encode($this->c_services),
    ];
    Clinic::create($input);
    $this->name = '';
    $this->c_services = '';
    $this->emit('clinicStore');
    session()->flash('message','! تم اضافة العيادة بنجاح ');
}

and my model is

class Clinic extends Model

{
use HasFactory;

protected $table = "clinics";

protected $fillable = ['name','c_services'];

public function services(){
    return $this->belongsToMany(ServiceData::class,'serv_clinics');
}

}

i’m using livewire and select2 and needs to store my services data into clinics table c_services attribute is a longText item

Source: Laravel

Leave a Reply