Created
February 15, 2019 08:29
-
-
Save zhuzhichao/a8e32f3297ee7635a470ce4f9afa0347 to your computer and use it in GitHub Desktop.
Laravel API 资源的匿名集合自定义处理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Resources; | |
use Illuminate\Http\Resources\Json\Resource; | |
use Illuminate\Pagination\AbstractPaginator; | |
class BaseResource extends Resource | |
{ | |
public static $wrap = false; | |
public static function collection($resource) | |
{ | |
$transformData = parent::collection($resource); | |
$responseData = [ | |
"code" => 0, | |
"message" => 'success', | |
]; | |
if ($resource instanceof AbstractPaginator) { | |
$paginated = $resource->toArray(); | |
return array_merge($responseData, [ | |
'meta' => [ | |
"total" => $paginated['total'], | |
"page" => $paginated['current_page'], | |
"page_size" => $paginated['per_page'], | |
], | |
'data' => $transformData, | |
]); | |
} | |
return array_merge($responseData, [ | |
"data" => $transformData, | |
]); | |
} | |
public static function collectionSuccess($resource, $message = null, $code = 0) | |
{ | |
$responseData = static::collection($resource); | |
$responseData['code'] = $code; | |
$responseData['message'] = $message ? : $responseData['message']; | |
return $responseData; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment