[英]Calculate percentage of two inputs in laravel
I want to calculate the percentage of two inputs which are total marks and obtained marks.我想计算两个输入的百分比,即总分和获得的分数。 When user fill these two inputs then in the percentage field i want to show the percentage automatically.当用户填写这两个输入时,我想在百分比字段中自动显示百分比。 I don't have the basic idea.我没有基本的想法。 Below is my controller下面是我的控制器
/** MyController.php */
public function store(ReportRequest $request)
{
$input = $request->all();
if ($file = $request->file('photo_id'))
{
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
Report::create($input);
return redirect()->back();
}
You can create a computed Accessor attribute in your Request
model class:您可以在Request
模型类中创建一个计算访问器属性:
/** Request.php */
public function getMarksPercentageAttribute
{
return (float) $this->obtained_marks / $this->total_marks;
}
So when you create your records.. you can use this attribute:所以当你创建你的记录时..你可以使用这个属性:
$request = Request:first();
dd($request->marks_percentage); // 0.35 for example
PS: I'm assuming that total_marks
and obtained_marks
are columns of your table. PS:我假设total_marks
和obtained_marks
是你的表列。 In case this aren't the correct names, replace this with the ones you actually use.如果这不是正确的名称,请将其替换为您实际使用的名称。
Note, after the creation of the element you are returning back.. you could redirect to a show
view for example.请注意,在您返回的元素创建后.. 例如,您可以重定向到一个show
视图。 From the docs :从文档:
Redirecting To Named Routes重定向到命名路由
When you call the
redirect
helper with no parameters, an instance ofIlluminate\\Routing\\Redirector
is returned, allowing you to call any method on theRedirector
instance.当你不带参数调用redirect
助手时,会返回一个Illuminate\\Routing\\Redirector
的实例,允许你调用Redirector
实例上的任何方法。 For example, to generate aRedirectResponse
to a named route, you may use theroute
method:例如,要生成对命名路由的RedirectResponse
,您可以使用route
方法:return redirect()->route('login');
If your route has parameters, you may pass them as the second argument to the route method:如果你的路由有参数,你可以将它们作为第二个参数传递给路由方法:
// For a route with the following URI: profile/{id} return redirect()->route('profile', ['id' => 1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.