私のモデルでこの特性を使用したい場合、ファイルを作成する場所
この特性を内部に持ちたい場合、このファイルはどのように見えますか?
trait FormatDates
{
protected $newDateFormat = 'd.m.Y H:i';
// save the date in UTC format in DB table
public function setCreatedAtAttribute($date){
$this->attributes['created_at'] = Carbon::parse($date);
}
// convert the UTC format to my format
public function getCreatedAtAttribute($date){
return Carbon::parse($date)->format($this->newDateFormat);
}
// save the date in UTC format in DB table
public function setUpdatedAtAttribute($date){
$this->attributes['updated_at'] = Carbon::parse($date);
}
// convert the UTC format to my format
public function getUpdatedAtAttribute($date){
return Carbon::parse($date)->format($this->newDateFormat);
}
// save the date in UTC format in DB table
public function setDeletedAtAttribute($date){
$this->attributes['deleted_at'] = Carbon::parse($date);
}
// convert the UTC format to my format
public function getDeletedAtAttribute($date){
return Carbon::parse($date)->format($this->newDateFormat);
}
}
そして、例えばUser Modelクラスでそれを適用する方法...
さて、laravelがPSR-4
に続くので、次の特性を配置する必要があります。
app/Traits
次に、そのパスでトレイトの名前空間を確認する必要があります。
namespace App\Traits;
trait
の上部
次に、ファイルを保存するときに、ファイル名が特性名と一致することを確認します。したがって、特性がFormatDates
と呼ばれる場合、ファイルをFormatDates.php
として保存する必要があります
次に、以下を追加して、ユーザーモデルで「使用」します。
use App\Traits\FormatDates;
モデルの最上部、ただしnamespace
の下
次に追加します:
use FormatDates;
クラスのすぐ内側なので、ユーザーモデルでは、laravel defaultを使用していると仮定すると、次のようになります。
use App\Traits\FormatDates;
class User extends Authenticatable
{
use Notifiable, FormatDates;
...
}
そして、オートローダーをダンプすることを忘れないでください:
composer dump-autoload