mardi 14 novembre 2017

Laravel - Update pivot table with additional values/checkbox array

I have a form that lists products that are available to add to a shopping list, along with an optional text field note for each product. A checkbox is used to select which products will be added to the shopping list.

The problem that I have is the first product checkbox MUST be ticked in order for the notes from subsequent products to be inserted into the product_shopping_list pivot table.

Controller

public function update($shoppingList)
{
    // Check if any product checkboxes ticked
    if (request('products'))
    {
        // Get products (array)
        $products = request('products');
        // Get notes (array)
        $notes = request('notes');
        // Get shopping list
        $shoppingList = ShoppingList::find($shoppingList);
        // Save (attach products to shopping list and notes)
        $sync_data = [];
        for ($i = 0; $i < count($products); $i++)
        {
            $sync_data[$products[$i]] = ['notes' => $notes[$i]];
        }
        $shoppingList->products()->attach($sync_data);
        // Message
        session()->flash(
            'message', 'Your products have been added to your list.'
        );
    } else {
        // If no checkboxes ticked
        session()->flash(
            'message', 'No products selected.'
        );
    }
    // Redirect
    return redirect()->route('shopping-list.show', $shoppingList);
}

View

@forelse ($products as $product)
    <div class="checkbox">
        <label for="products">
        {!! Form::checkbox('products[]', $product->id, false) !!}
        @if ($product->essential)
            <span class="essential"></span>
        @else
            
        @endif
        </label>
    </div>
    <div class="form-group">
        {!! Form::label('notes', 'Note') !!}
        {!! Form::text('notes[]', null, [
            'class' => 'form-control',
            'placeholder' => 'Note'
        ]) !!}
    </div>

@empty
    <div class="alert alert-info" role="alert">
        There are no available products.
    </div>
@endforelse

Pivot table schema

Schema::create('product_shopping_list', function (Blueprint $table) {
    $table->unsignedInteger('product_id');
    $table->unsignedInteger('shopping_list_id');
    $table->string('notes')->nullable();
    $table->primary(['product_id', 'shopping_list_id']);
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
    $table->foreign('shopping_list_id')->references('id')->on('shopping_lists')->onDelete('cascade');
});




Aucun commentaire:

Enregistrer un commentaire