2015-12-14 76 views
2

讓我的表設置時間戳字段用於在字段中創建和更新。Laravel日期不允許我使用diffForHumans

在我的模型然後我做到這一點:

protected $dates = ['created_at', 'updated_at']; 

但調用的日期:

$p->created_at->diffForHumans() 

我得到

Call to a member function diffForHumans() on string 

我敢肯定,應該工作。我曾經在不同的模型等使用過相同的許多次,但這是行不通的。

+1

你其實並不需要列出'created_at'和'updated_at'在'$ dates'財產。 Laravel已經在幕後爲你處理這件事。無論如何,你是否可能改變或鑄造屬性? –

+0

或者使用非雄辯模型查詢獲取記錄? DB ::語句可能不會轉換這些值。 –

回答

0

你必須使用Carbon,像這樣:

$date = new \Carbon($p->created_at)->diffForHumans(); 
+2

默認情況下,'Eloquent'將'$ dates'中的日期屬性轉換爲'Carbon',所以它應該使用'$ p-> created_at-> diffForHumans()'來工作,因爲'created_at'可以在'$ dates'屬性中獲得這些假設是'碳'instaan​​ces。 –

4

默認情況下,雄辯會轉換created_at和的updated_at到碳,它提供了有用的方法各式各樣的實例列,並擴展了原生PHP的DateTime類。

閱讀:https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

只是檢查nesbot /炭包你composer.json文件。在情況下,如果你沒有,你可以通過鍵入

composer require nesbot/carbon 

替代的解決方案是安裝它,

你可以使用碳::解析()來動態地創建對象。

Carbon::parse($p->created_at)->diffForHumans(); 
5

我在5.2版本已經使用了Laravel diffForHumans()功能,只有當您使用的是created_atupdated_at工作,否則會帶來你的Call to a member function diffForHumans() on string錯誤。即使你已經使用了created_atupdated_at,只要確定你的遷移,你還沒有使用:

$table->timestamp('created_at'); 
$table->timestamp('updated_at'); 

但你有沒有根據laravel 差異使用

$table->timestamps(); 

但由於某種原因,您想對某個既不是created_atupdated_at,的列使用diffForHumans()函數。例如expired_at,使用碳

我可以總結說的是:

  1. 首先創建一個新的文件夾可以被稱爲在laravel項目文件夾如測試laravel Addon
  2. 那麼文件夾內,您創建一個名爲Carbon.php的新文件。
  3. 裏面的Carbon.php文件,輸入:

namespace Carbon; 

class Carbon extends \DateTime{ 
    // 
} 

然後轉到您的控制器ProductController.php和碳命名空間添加到文件:


namespace Addon; 
namespace App\Http\Controllers; 

use Carbon\Carbon; 
use ... 

class ProductController extends Controller{ 
    $expire_date_string = '2016-07-27 12:45:32'; 
    // Parse date with carbon 
    $carbonated_date = Carbon::parse($expire_date_string); 
    // Assuming today was 2016-07-27 12:45:32 
    $diff_date = $carbonated_date->diffForHumans(Carbon::now()); 
    echo $diff_date; // prints "1 month after" 
} 

有關Ca的更多信息rbon控制器,請訪問:http://carbon.nesbot.com/docs/

2

你並不需要使用碳一列既不created_at和的updated_at就像expired_at添加新列到你的模型:

/** 
* The attributes that should be mutated to dates. 
* 
* @var array 
*/ 
protected $dates = [ 
    'created_at', 
    'updated_at', 
    'deleted_at', 
    'expired_at' 
]; 

然後你就可以使用 - > diffForHumans();

https://laravel.com/docs/5.3/eloquent-mutators#date-mutators