bigsinoos / j-eloquent
实时将eloquent日期属性转换为贾拉利(波斯)日期。(支持模型属性访问、toJson、toString和toArray)。
Requires
- illuminate/database: 5.1.* || 5.2.* || 5.3.* || 5.4.*
- miladr/jalali: 0.*
This package is not auto-updated.
Last update: 2024-09-14 15:46:48 UTC
README
弃用通知
对于Laravel的新版本,只需使用简单的属性转换功能即可,这是一种更优雅的方法。
什么是j-Eloquent?
感谢Laravel、Django和Rails,我们都知道约定优于配置(CoC)使开发更有趣。假设你想将你的Eloquent
模型的公历日期属性转换为贾拉利(波斯)日期,在这种情况下,j-Eloquent
可以帮助你按约定进行转换,例如,当你在模型上访问名为$model->jalali_created_at
的属性时,PersianDateTrait
会自动检测约定并尝试转换你的模型的created_at
属性,如果它是日期属性。这也适用于$model->toJson();
和$model->toArray();
字段。
安装
在你的composer require
部分添加以下行
"require" : { // Other dependecies , "bigsinoos/j-eloquent" : "dev-master" // Laravel 5 , "1.0" for Laravel 4 }
要求
此包需要:miladr/jalali
功能
- 在访问以字符串如
jalali_
为前缀的原始日期属性时, conventionally 将Eloquent模型日期属性转换为贾拉利日期。 - 当模型调用
toArrayl
、__toString();
和toJson
时,自动将日期属性转换为贾拉利日期。 - 可以为日期设置自定义日期格式。
文档
PersianDateTrait
通过在你的模型中使用\Bigsinoos\JEloquent\PersianDateTrait
特性来启用插件
<?php class Role extends \Eloquent { use \Bigsinoos\JEloquent\PersianDateTrait; protected $table = 'roles'; }
用法
默认情况下,你可以通过在原始属性名称前添加jalali_
子字符串来以贾拉利日期访问你的eloquent日期属性,如jalali_created_at
$userPremiumRole = Auth::user()->roles()->where('type', 'premium'); $userPremiumRole->create_at; // 2014/12/30 22:12:34 $userPremiumRole->jalali_created_at; // 93/09/08
更改jalali_
前缀
你可以通过重写$model->setJalaliFormat($format)
和$model->getJalaliFormat();
或通过重写你的模型类上的$model->jalaliDateFormat
属性来更改贾拉利日期约定前缀
class Role extends \Eloquent { use \Bigsinoos\JEloquent\PersianDateTrait; protected $jalaliDateFormat = 'l j F Y H:i'; } # or class Role extends \Eloquent { use \Bigsinoos\JEloquent\PersianDateTrait; public function setJalaliFormat($format){ // do custom things here $this->jalaliDateFormat = $format; return $this; } protected function getJalaliFormat() { // return any format you want return 'l j F Y H:i'; } }
自定义日期属性
你可以告诉Eloquent哪些字段是日期属性,如created_at和updated_at,然后Eloquent将它们视为你定义的多个日期属性,如下所示
Class Role extends \Eloquent { use \Bigsinoos\JEloquent\PersianDateTrait; /** * Add this method to customize your date attributes * * @return array */ protected function getDates() { return ['created_at', 'updated_at', 'expired_at']; } }
当使用上述特性时,所有由Laravel处理的日期对象字段都将可用进行常规转换。它们也将添加到模型的toJson()
、toArray();
和__toString();
方法中。
转换辅助方法
$model->convertToPersian($attribute, $format);
方法允许你正常地将字段从公历日期转换为贾拉利日期
$user = Auth::user(); $user->convertToPersian('created_at', 'y/m/d'); // 93/09/08