如何计算 Laravel 数据库中所有行的剩余天数

问题描述 投票:0回答:1

我正在尝试创建一个基于 Laravel 的项目,因为我有一个部分来显示剩余的天数...我的数据库中有 3 列;他们是

  • sub_start_date
    (表示订阅开始日期)
  • sub_end_date
    (表示订阅结束日期)
  • subscription_type
    (应该是1个月、2个月、3个月的选择框)。

其中

sub_end_date
是在 jQuery 的帮助下自动计算的。因此它将存储在数据库中为 1-9-2020 (M-D-Y).

所以我的问题是我无法计算剩余的天数。我用谷歌搜索并得到了一些类似的解决方案,我将在下面添加,但它仅适用于一行(或适用于我们最后添加的行)。在我的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

每列剩余天数为 260 天。

请帮我找到解决办法

database laravel datediff
1个回答
2
投票

在您的客户模型中定义了 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
© www.soinside.com 2019 - 2024. All rights reserved.