0

Please help, so i want to use foreach to loop and attach data to database using Eloquent in my Controller, i passed this is the parsed data as an array :

array:3 [▼
  0 => "3"
  1 => "7"
  2 => "9"
]

and i want to loop (foreach) and save it to tables using attach() so it can be saved with the same ID in one time like this :

Course_ID | Facilitator_Id
--------------------------
1         | 2
1         | 3
1         | 4
--------------------------

this is the piece of blade :

<form method="POST" action="{{ '/courses' }}" enctype="multipart/form-data">
...
                            <div class="form-group row">
                            <label class="col-3" for="fasil_id">Fasilitator</label>
                            <div class="col-9">
                                <select class="form-control @error('fasil_id') is-invalid @enderror bootstrap-select" data-style="btn-white" multiple name="fasil_id[]" selected="{{ old('fasil_id') }}" required autocomplete="fasil_id">
                                 @foreach($facilitators as $data)
                                  <option value="{{$data->id}}">{{$data->nama}}</option>
                                 @endforeach
                                </select>
                                @error('fasil_id')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror
                            </div>
                        </div>
...
</form>
  • im using name="fasil_id[]" in the markup properties

  • and currently i'm using this method for looping :

     foreach($request->fasil_id as $fasil_id) {
     Course::find($id)->facilitators()->attach([$fasil_id]); }
    

but, sadly i always get this error :

htmlspecialchars() expects parameter 1 to be string, array given
1
  • Instead of ->attach([$fasil_id]) use ->attach($fasil_id). Commented Dec 22, 2020 at 16:51

1 Answer 1

1

In your <select> opening tag you are setting selected="{{ old('fasil_id') }}".
But since fasil_id is an array it cannot be set as the selected value and {{ }} cannot print it.
Try to remove selected="{{ old('fasil_id').

As a side note: You can pass an array to the attach() method so you don't need to loop here. Just do it like this:

 Course::find($id)->facilitators()->attach($request->fasil_id); 
Sign up to request clarification or add additional context in comments.

1 Comment

wow, it really worked! Thank you for your help, i didn't know you can pass an array using attach() without looping, thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.