database - 如何计算数据库中所有原始数据在laravel中剩余的天数
问题描述
亲爱的,
我正在尝试创建一个基于 laravel 的项目,其中我有一个部分来显示剩余的天数......我的数据库中有 3 个 coloums 它们是
- sub_start_date(表示订阅开始日期)
- sub_end_date(表示订阅结束日期)
- 订阅类型(对应的1个月、2个月和3个月应该是一个选择框)。
其中sub_end_date是在 jQuery 的帮助下自动计算的。因此它将存储在 db As 1-9-2020 (MDY)中。所以我的问题是我无法计算剩余的天数..我已经用谷歌搜索并得到了一些类似的解决方案,我将在下面添加但它仅适用于一行(或我们将在最后添加的行)并且在我的 Blade.php页面它在循环中显示相同的结果..
//subscription_details.blade.php
@extends('layouts.app')
@section('body')
<center>
</br>
<div class="col-lg-5">
<h4>subscribtion details</h4></br>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Phone Number</th>
<th scope="col">Type Of Subscription</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Days Remaining</th>
</tr>
</thead>
<tbody>
<tr>
@foreach($customer as $row)
<th scope="row">{{$row->name}}</th>
<td>{{$row->phone}}</td>
<td>{{$row->subscription}}Month</td>
<td>{{$row->sub_start_date}}</td>
<td>{{$row->sub_end_date}}</td>
<td>{{$count}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</center>
@endsection
我的控制器代码是
//SubscriptionController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\customer;
use Carbon\Carbon ;
class SubscriptionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$now = Carbon::now();
$customer =customer::all();
foreach($customer as $row)
{
$end_date = $row->sub_end_date;
$cDate = Carbon::parse($end_date);
$count = $now->diffInDays($cDate );
}
return view('subscription_details',compact('customer','count'));
}
到目前为止,我得到了这个
订阅详情
结果就像 Sub_start date = 2019-12-01,Sub_end date =2019-12-01 days 剩余的每个coloum 260天 请帮我找到解决方案
解决方案
在您的客户模型中定义了一个mutator属性:
use Carbon\Carbon;
...
public function getRemainingDaysAttribute()
{
if ($this->sub_end_date) {
$remaining_days = Carbon::now()->diffInDays(Carbon::parse($this->sub_end_date));
} else {
$remaining_days = 0;
}
return $remaining_days;
}
在您的控制器中,只需带您的客户:
public function index()
{
$customer =customer::all();
return view('subscription_details',compact('customer'));
}
在你看来:
@foreach($customer as $row)
<th scope="row">{{$row->name}}</th>
<td>{{$row->phone}}</td>
<td>{{$row->subscription}}Month</td>
<td>{{$row->sub_start_date}}</td>
<td>{{$row->sub_end_date}}</td>
<td>{{$row->remaining_days}}</td>
</tr>
@endforeach
推荐阅读
- react-native-fbsdk - 来自 ShareDialog 的 react-native postId null
- php - 如何获得关系表的平均值?拉拉维尔
- javascript - JavaScript - Pdf Generation / Print 好的,现在我想要将文档下载为 PDF 文件
- angular - 如何在 Angular App 上显示 Git 分支名称
- graph - 仪表板图形数据源
- python - Python递归问题【leetcode问题】
- reactjs - 使用反应挂钩表单提交后显示输入
- python - 使用 playsound 模块时程序崩溃
- python - 部署后烧瓶的uWSGI-apscheduler问题,因为招摇页面抛出502错误
- mysql - 如何在 postgres 和 MySQL 中使用 node jdbc 模块?