首页 > 解决方案 > 如何计算数据库中所有原始数据在laravel中剩余的天数

问题描述

亲爱的,

我正在尝试创建一个基于 laravel 的项目,其中我有一个部分来显示剩余的天数......我的数据库中有 3 个 coloums 它们是

其中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-01Sub_end date =2019-12-01 days 剩余的每个coloum 260天 请帮我找到解决方案

标签: databaselaraveldatediff

解决方案


在您的客户模型中定义了一个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

推荐阅读