【发布时间】:2019-09-02 14:56:46
【问题描述】:
我有一个名为“产品”的表,其中包含 5 个字段(id、标题、价格、数量、总计)。
我的目标是通过 products.create 的形式计算总数,价格 * 数量。
数据库 - 产品
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>
感谢您的帮助。
【问题讨论】:
-
你想在哪里显示总数?在
setTotalAttribute()中,您可能应该有$this->attributes['total'] = $this->quantity * $this->price;。 Defining A Mutator.
标签: laravel