laravel dateinterval cast
vel 8.x Support
Laravel 有內建的date
和datetime
類型轉換,但如果您想將 ISO 8061 持續時間與本機DateInterval
類別或 Carbon 的CarbonInterval
一起使用,那麼您就不走運了。
該套件使用 Laravel 7.x/8.x 的自訂轉換功能提供了兩個自訂轉換(分別針對DateInterval
和CarbonInterval
)。
composer require atymic/laravel-dateinterval-cast
在模型的$casts
中,將您希望啟用強制轉換的屬性指派給套件提供的任一強制轉換。您應該在資料庫表中使用varchar
/ string
欄位。
class TestModel extends Model
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $ casts = [
' is_xyz ' => ' boolean ' ,
' date_interval ' => DateIntervalCast::class,
' carbon_interval ' => CarbonIntervalCast::class,
];
}
然後,模型上的屬性將轉換為間隔對象,並作為 ISO 8061 持續時間字串儲存到資料庫中。如果您嘗試指派無效的持續時間(或資料庫表包含一個持續時間,並且您使用 getter),則會引發例外狀況。
$ model = new TestModel ();
$ model -> carbon_interval = now ()-> subHours ( 3 )-> diffAsCarbonInterval ();
$ model -> save (); // Saved as `P3H`
$ model -> fresh ();
$ model -> carbon_interval ; // Instance of `CarbonInterval`
$ model -> carbon_interval -> forHumans (); // prints '3 hours ago'
try {
$ model -> carbon_interval = ' not_a_iso_period ' ;
} catch ( Atymic DateIntervalCast Exception InvalidIsoDuration $ e ) {
// Exception thrown if you try to assign an invalid duration
}
歡迎貢獻:) 請建立一個 PR,我將審查/合併它。
麻省理工學院