简体   繁体   中英

How to save array data from multiple select in Laravel using Eloquent

i'd like to save data from multiple select to the database. So a user can choose more than one products in a multiple select. I've tried the code like below but i got this error "ErrorException Array to string conversion". Here is my blade.php

<div class="form-group row" style="display:none;" id="inputbarang">
<label class="col-form-label col-lg-3 col-sm-12">Barang</label>
    <div class="col-lg-4 col-md-9 col-sm-12">
        <select class="form-control m-select2" width="500px" id="kt_select2_1" name="id_product[]" multiple="multiple">
                <option value=""></option>
                @foreach($produk as $p)
                <option value="{{ $p->id }}">{{ $p->product }}</option>
                @endforeach
        </select>
    </div>
</div>

and here is my controller

$id_promo = Promo::select('id')
   ->where('delete', 0)->orderBy('created_at', 'DESC')
   // ->take(1)
   ->pluck('id')->first();

   $id_product = [];
   $id_product[] = $request->id_product;

   // $id_products = $id_product['id_product'];

   foreach ($id_product as $i) {
           DetailPromo::create([
           'id_promo' => $id_promo,
           'id_product' => $i,
           'det_potongan' => $request->potongan,
           'det_jumlah_potongan' => $request->jumlah_potongan
       ]);
       }

Any helps will be appreciated, thank you so much

Try below code:

$id_promo = Promo::select('id')
    ->where('delete', 0)
    ->orderBy('created_at', 'DESC')
    // ->take(1)
    ->pluck('id')
    ->first()
;

$id_products = $request->id_product;
foreach ($id_products as $id_product) {
    DetailPromo::create([
        'id_promo' => $id_promo,
        'id_product' => $id_product,
        'det_potongan' => $request->potongan,
        'det_jumlah_potongan' => $request->jumlah_potongan
    ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM