サンプルコード
public function toArray($id)
{
return [
'id'=>$this -> id,
'title'=>$this -> title,
'body'=>$this -> body,
'tag'=>$this -> tag,
'seo_title'=>$this -> seo_title,
'meta_description'=>$this -> meta_description,
'featured_image'=>$this -> featured_image,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
上記なようなコントローラー作成してgetしてしみると
{
"data": {
"id": 2,
"title": null,
"body": null,
"tag": null,
"seo_title": null,
"meta_description": null,
"featured_image": "https://headlesscms-api.s3.ap-northeast-1.amazonaws.com/test/BBjbX0ocpy3oWVGl5z05zRNzS9FoALqhmkJo1xKv.png",
"created_at": {
"date": "2019-07-15 01:40:07.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2019-07-15 01:40:07.000000",
"timezone_type": 3,
"timezone": "UTC"
}
}
}
created_at
,updated_at
に"timezone_type"
,"timezone"
がついてしまいます。
dateのみにしたい時
Carbonを使う
CarbonとはPHPのDateTimeクラスをオーバーラップした日付操作ライブラリです。
<?php
namespace App\Http\Resources;
use \App\Post;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\Resource;
class ApiPostsCollection extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($id)
{
return [
'id'=>$this -> id,
'title'=>$this -> title,
'body'=>$this -> body,
'tag'=>$this -> tag,
'seo_title'=>$this -> seo_title,
'meta_description'=>$this -> meta_description,
'featured_image'=>$this -> featured_image,
'created_at' => (new Carbon($this->created_at))->toDateTimeString(),
'updated_at' => (new Carbon($this->updated_at))->toDateTimeString(),
];
}
}
use Carbon\Carbon;
'created_at' => (new Carbon($this->created_at))->toDateTimeString(),
'updated_at' => (new Carbon($this->updated_at))->toDateTimeString(),
上記のようにCarbon使用したdateのみ返せるようになります。
{
"data": {
"id": 2,
"title": null,
"body": null,
"tag": null,
"seo_title": null,
"meta_description": null,
"featured_image": "https://headlesscms-api.s3.ap-northeast-1.amazonaws.com/test/BBjbX0ocpy3oWVGl5z05zRNzS9FoALqhmkJo1xKv.png",
"created_at": "2019-07-15 01:40:07",
"updated_at": "2019-07-15 01:40:07"
}
}