从数据库访问数据以与当前日期进行比较以计算总天数

access data from database to compare with current date to calculate total days

我试图访问存储在我的数据库中的日期 table 并将其与当前日期进行比较,以便我可以获得天数,但它显示此错误

DateTime::__construct(): Failed to parse time string ([{"quit_date":null},{"quit_date":null}]) at position 0 ([): Unexpected character

这是在我的控制器中使用的代码

$quit_date = Information::select('quit_date')
             ->where('user_id','=',\Auth::user()->id)
             ->get();
$date = new Carbon($quit_date);
$now = Carbon::now();
        $day = $date->diffInDays($now);

但是如果我用日期手动设置 $quit_date 例如 "2019-04-25 00:00:00.000000",代码工作正常并显示日期之间不同的日期,但是当我使用 Information::select 从数据库中读取日期时,它显示错误。

    use Auth;     //top of controller
    $checkdate = Information::
            ->where('user_id','=',Auth::user()->id)
            ->first();
    $quit_date=$checkdate->quit_date;
    $date = new Carbon($quit_date);
    $now = Carbon::now();
    $day = $date->diffInDays($now);

出现此问题是因为您在查询末尾使用了 ->get()。该方法 return 是 Collection 而不是单个对象。通过使用 ->first() 到 return 单个对象解决了这个问题。

错误本身是因为在 $date = new Carbon($quit_date); 行中,Carbon 无法将 Collection 转换为日期。

这应该有效:

$quit_date = Information::select('quit_date')
             ->where('user_id','=', \Auth::user()->id)
             ->first();    //Changed this from ->get()
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);