I'm trying to insert records to pivot table from checkboxes and texboxes. Foreach checkbox has one textbox attached.
My blade:
@foreach(Stock::all() as $stock)
<div class="form-check">
<input class="form-check-input stockCheckbox" type="checkbox" name="stock_id[]" value="{{$stock->id}}" id="{{$stock->id}}">
<label class="form-check-label" for="stock_id">
{{$stock->name}}
</label>
</div>
<div class="form-group" id="qtySpentField">
<input type="text" class="form-control" name="qtySpent" id="qtySpent" value="" placeholder="qtySpent">
</div>
@endforeach
Model for Products:
class Produktet extends Model
{
public function stocks()
{
return $this->belongsToMany('App\Stock')->withPivot('qtySpent')->withTimestamps();
}
}
Model for Stock:
class Stock extends Model
{
public function produktets(){
return $this->belongsToMany('App\Produktet')->withTimestamps();
}
}
My pivot table:
Schema::create('produktet_stock', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('produktet_id');
$table->foreign('produktet_id')
->references('id')
->on('produktets')->onDelete('cascade');
$table->string('stock_id');
$table->foreign('stock_id')
->references('id')
->on('stocks')->onDelete('cascade');
$table->double('qtySpent', 8, 2);
$table->timestamps();
});
As you can see, I have an additional column in my pivot table called "qtySpent"
My controller:
$prod = new Produktet;
$prod->stocks()->sync($req->input('stock_id'), $req->input('qtySpent'));
The problem is that it is inserting only stock_id values in multiple rows, but in the qtySpent column it is not inserting any value only null.
id| produktet_id | stock_id | qtySpent
=====================================
1 1 1 null
2 1 2 null
3 1 3 null
So, I have to fill pivot table with stock_id values and qtySpent values in multiple rows. For example: When I check two checkboxes(for stock_id), I will write also qtySpent values in text fields and these records should be inserted in pivot table. The pivot table should fill like this:
id| produktet_id | stock_id | qtySpent
=====================================
1 1 1 0.1
2 1 2 0.1
3 1 3 0.2