Значения, не обновленные в базе данных

#php #laravel #laravel-blade

Вопрос:

У меня есть таблица атрибутов продукта, в которой у меня есть 2 текстовых поля. Поэтому, когда я ввожу значения во все поле текстового поля. И когда я нажимаю кнопку обновления. первая строка ввода успешно обновлена, а остальные-нет. Вот изображение файла с лезвием:

введите описание изображения здесь

Вот мой код Blade.php

 <form name="editAttributeForm" id="editAttributeForm" method="post" action="{{url('admin/edit-attributes/'.$productdata['id'])}}" enctype="multipart/form-data">
            @csrf
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Added Product Attributes</h3>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                    <table id="products" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Size</th>
                                <th>SKU</th>
                                <th>Price</th>
                                <th>Stock</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($productdata['attributes'] as $attribute)
                            <!-- getting the attribute fields ids  -->
                            <input style="display: none;" type="text" name="attrId[]" value="{{$attribute['id']}}">
                            <tr>
                                <td>{{$attribute['id']}}</td>
                                <td>{{$attribute['size']}}</td>
                                <td>{{$attribute['sku']}}</td>
                                <td>
                                    <input type="number" name="price[]" value="{{$attribute['price']}}" required="">
                                </td>
                                <td>
                                    <input type="number" name="stock[]" value="{{$attribute['stock']}}" required="">
                                </td>
                                <td>
                                    @if($attribute['status']==1)
                                    <a class="updateAttributeStatus" id="attribute-{{$attribute['id']}}" attribute_id="{{$attribute['id']}}" href="javascript:void(0)"><i class="fas fa-toggle-on" aria-hidden='true' status="Active"></i></a>
                                    @else
                                    <a class="updateAttributeStatus" id="attribute-{{$attribute['id']}}" attribute_id="{{$attribute['id']}}" href="javascript:void(0)"><i class="fas fa-toggle-off" aria-hidden='true' status="Inactive"></i></a>
                                    @endif
                                    amp;nbsp;
                                    <a href="javascript:void(0)" class="confirmDelete" record="attribute" recordid="{{$attribute['id']}}" title="Delete Product"><i class="far fa-trash-alt text-danger"></i></a>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">
                    <button type="submit" class="btn btn-warning">Update Attributes</button>
                </div>
            </div>
            <!-- /.card -->
        </form>
 

ProductsController.php

 public function editAttributes(Request $request, $id)
{
    if ($request->isMethod('post')) {
        $data = $request->all();
        // echo "<pre>";
        // print_r($data);
        // die;

        foreach ($data['attrId'] as $key => $attr) {
            if (!empty($attr)) {
                ProductsAttribute::where(['id' => $data['attrId'][$key]])->update(['price' => $data['price'][$key], 'stock' => $data['stock'][$key]]);
            }

            $success_message = "Product attributes has been updated successfully!";
            session::flash("attSuccess_message", $success_message);
            return redirect()->back();
        }
    }
}
 

Комментарии:

1. у вас есть цикл, и вы выходите из него, и сам метод на первой итерации с return оператором

Ответ №1:

Обновите свой ProductsController.php , как показано ниже, это может сработать.

 public function editAttributes(Request $request, $id)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            foreach ($data['attrId'] as $key => $attr) {
                if (!empty($attr)) {
                    ProductsAttribute::where(['id' => $data['attrId'][$key]])
                        ->update(['price' => $data['price'][$key], 'stock' => $data['stock'][$key]]);
                }
            }

            // You can check all attributes, updated or not if you wish
            
            $success_message = "Product attributes has been updated successfully!";
            session::flash("attSuccess_message", $success_message);
            return redirect()->back();
        }
    }
 

Комментарии:

1. » это может сработать «, А может и нет? В чем была проблема? Что ты изменил?

2. Как он сказал, 1-я строка работает, что означает, что его код работает, но возникла небольшая проблема с оператором return в цикле, пожалуйста, проверьте мой блок кода @brombeer