我有一个名为“产品”的表格,其中有5个字段(编号,标题,价格,数量,总计)。
我的目标是通过产品表格进行计算。创建总价*数量。
数据库-产品
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->integer('quantity');
$table->double('price');
$table->double('total')->nullable();
$table->timestamps();
});
}
型号-产品
protected $fillable = ['title', 'quantity', 'price', 'total'];
public function setTotalAttribute()
{
$this->total = $this->quantity * $this->price;
}
public function getTotalAttribute($value)
{
return $value;
}
**控制器-ProductController **
public function index()
{
$products = Product::oldest()->paginate(5);
return view('admin.products.index', compact('products'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
$products = Product::all();
return view('admin.products.create', compact('products'));
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
'total' => 'required'
]);
Product::create($request->all());
return redirect()->route('products.index')
->with('success', 'save');
}
我的问题是在我的视图“ products.create”中,当我对3个字段进行编码时,我有3个字段,什么都没有发生?
Products.create
<form class="panel-body" action="{{route('products.store')}}" method="POST" novalidate>
@csrf
<fieldset class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="form-group-input-1">Title</label>
<input type="text" name="title" id="title" class="form-control" value="{{ old('title')}}"/>
{!! $errors->first('title', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="form-group-input-1">Quantity</label>
<input type="text" name="quantity" id="quantity" class="form-control" value="{{ old('quantity')}}"/>
{!! $errors->first('quantity', '<span class="help-block">:message</span>') !!}
</fieldset>
<fieldset class="form-group {{ $errors->has('price') ? 'has-error' : '' }}">
<label for="form-group-input-1">Price</label>
<input type="text" name="price" id="price" class="form-control" value="{{ old('price')}}"/>
{!! $errors->first('price', '<span class="help-block">:message</span>') !!}
</fieldset>
<a href="{{route('products.index')}}" class="btn btn-primary pull-right">Back</a>
<button type="submit" class="btn btn-sm btn-primary">Valider</button>
谢谢您的帮助。
答案 0 :(得分:0)
首先,您没有发送任何总值...
$request->validate([
'title' => 'required',
'quantity' => 'required',
'price' => 'required',
]);
只需遵循雄辩的ORM
$product = New Product();
$product-title = $request->title;
$product-quantity = $request->quantity;
$product-price = $request->price;
$product-total = $request->price * $request* quantity;
$product->save();
// redirect()
答案 1 :(得分:0)
增变器将收到在属性上设置的值,因此您的Product
模型上的增变器方法应与此类似
public function setTotalAttribute()
{
$this->attributes['total'] = $this->quantity * $this->price;
}