问题描述
我的Laravel-5.8中有这些模型
产品型号:
class Product extends Model
{
protected $fillable = [
'id','name',];
public function invoice(){
return $this->belongsToMany('App\Invoice');
}
}
发票型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
protected $fillable = [
'id','customer_id','product_id','invoice_date','qty','price',];
public function customer(){
return $this->belongsTo('App\Customer');
}
public function product(){
return $this->belongsToMany('App\Product');
}
}
每张发票都有一个或多个产品。
发票管理员
public function create()
{
$customers = Customer::all();
$products = Product::all();
return view('invoice.create',compact('customers','products'));
}
public function store(Request $request)
{
$request->validate([
'customer_id' => 'required','product_id' => 'required','qty' => 'required','price' => 'required',]);
$invoice = new Invoice();
$invoice->customer_id = $request->customer_id;
.....
return redirect('invoice/'.$invoice->id)->with('message','invoice created Successfully');
}
发票:create.blade
<form method="POST" action="{{route('invoice.store')}}">
@csrf
<div class="form-group col-md-3">
<label class="control-label">Customer Name</label>
<select name="customer_id" class="form-control">
<option>Select Customer</option>
@foreach($customers as $customer)
<option name="customer_id" value="{{$customer->id}}">{{$customer->name}} </option>
@endforeach
</select> </div>
<div class="form-group col-md-3">
<label class="control-label">Date</label>
<input name="invoice_date" class="form-control datepicker" value="<?php echo date('Y-m-d')?>" type="date" placeholder="Enter date">
</div>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Qty</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="product_id[]" class="form-control productname" >
<option>Select Product</option>
@foreach($products as $product)
<option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
@endforeach
</select></td>
<td><input type="text" name="qty[]" class="form-control qty" ></td>
<td><input type="text" name="price[]" class="form-control price" ></td>
</tr>
</tbody>
</table>
<div >
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
从下图开始:
Product_id,数量,价格是数组。 我希望控制器迭代并计算产品数量,然后视图中的product_id,qty和price行将基于产品数量。然后所有内容都将保存在发票表中。
如何完成我的商店控制器代码来实现这一目标?
解决方法
尝试一下:
$products = $request->get('product_id');
$qte = $request->get('qty');
$price = $request->get('price');
foreach($products as $key=>$product){
$invoice =Invoice::creeate([
'product_id' => $product,'qte' => $qte[$key],'price' => $price[$key],...
]);
}