Hello i am wondering if its possible to have an array in view blade that is filled with values that user selects and then to be passed to controller. I am asking if its possible to do such a thing and avoid this type of code i already have that works:
foreach ($request->products as $index => $product) {
$values[] = [
'order_id' => $order->id,
'product_id' => $product,
'amount' => $request->amount[$index],
];
So for the foreach i dont need to write $index => $product
This is the request that comes from view:
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
'products' => 'required|exists:products,id',
'amount' => 'required',
]);
And this is the view im using:
<div class="row mb-3">
<label for="products" class="col-md-4 col-form-label text-md-end">{{ __('Product') }}</label>
<div class="col-md-6">
<select name="products[]" id="products" type="text" class="form-control @error('products') is-invalid @enderror" required autocomplete="products">
@foreach($products as $product)
<option value="{{$product->id}}">{{$product->name}}</option>
@endforeach
</select>
@error('products')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="amount" class="col-md-4 col-form-label text-md-end">{{ __('Amount') }}</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control @error('amount') is-invalid @enderror" name="amount[]" required autocomplete="amount">
@error('amount')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
2
Answers
If I understand your question correctly, you want to avoid JQuery? It depends on what environment and language you’re using. In ASP .NET Core you can use a hidden input field and pass something through as text.
Then in your controller you can deserialize it (C# example).
Maybe that’s what you’re looking for but it really depends on what you’re doing, which I’m not sure about.
We can use the input name to create an associative array using the
product id
as the key in the array.You can achieve this by subbing in the product id for the array index and labelling the fields that will go into it.
This will product a structure like
While you will still have to iterate using
foreach($request->products as $productID => $data)
the data structure is all relational regarding where the data is stored.