Created
September 7, 2017 05:47
-
-
Save developerdino/400d7523a6f0973d2ba67b52ff3e4e28 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 App\Comment; | |
use App\People; | |
use Illuminate\Http\Resources\Json\ResourceCollection; | |
use Illuminate\Support\Collection; | |
class ArticlesResource extends ResourceCollection | |
{ | |
/** | |
* Transform the resource collection into an array. | |
* | |
* @param \Illuminate\Http\Request | |
* | |
* @return array | |
*/ | |
public function toArray($request) | |
{ | |
return [ | |
'data' => ArticleResource::collection($this->collection), | |
]; | |
} | |
public function with($request) | |
{ | |
$comments = $this->collection->flatMap( | |
function ($article) { | |
return $article->comments; | |
} | |
); | |
$authors = $this->collection->map( | |
function ($article) { | |
return $article->author; | |
} | |
); | |
$included = $authors->merge($comments)->unique(); | |
return [ | |
'links' => [ | |
'self' => route('articles.index'), | |
], | |
'included' => $this->withIncluded($included), | |
]; | |
} | |
private function withIncluded(Collection $included) | |
{ | |
return $included->map( | |
function ($include) { | |
if ($include instanceof People) { | |
return new PeopleResource($include); | |
} | |
if ($include instanceof Comment) { | |
return new CommentResource($include); | |
} | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment