Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.5] Add ability to pass callback to whenLoaded Resource method #21490

Merged
merged 2 commits into from
Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,18 +111,34 @@ protected function attributes($attributes)
}

/**
* Retrieve a relationship if it has been loaded.
* Retrieve a relationship or execute a callback
* if the given relationship has been loaded.
*
* @param string $relationship
* @param mixed $value
* @param mixed $default
*
* @return \Illuminate\Http\Resources\MissingValue|mixed
*/
protected function whenLoaded($relationship)
protected function whenLoaded($relationship, $value = null, $default = null)
{
if ($this->resource->relationLoaded($relationship)) {
if (func_num_args() < 3) {
$default = new MissingValue;
}

if (! $this->resource->relationLoaded($relationship)) {
return $default;
}

if (func_num_args() === 1) {
return $this->resource->{$relationship};
}

return new MissingValue;
if ($this->resource->{$relationship} === null) {
return null;
}

return value($value);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ public function toArray($request)
'id' => $this->id,
'comments' => new CommentCollection($this->whenLoaded('comments')),
'author' => new AuthorResource($this->whenLoaded('author')),
'author_name' => $this->whenLoaded('author', function () {
return $this->author->name;
}),
];
}
}
2 changes: 2 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ public function test_resources_may_load_optional_relationships()
'data' => [
'id' => 5,
'author' => ['name' => 'jrrmartin'],
'author_name' => 'jrrmartin',
],
]);
}
Expand Down Expand Up @@ -184,6 +185,7 @@ public function test_resources_may_shows_null_for_loaded_relationship_with_value
'data' => [
'id' => 5,
'author' => null,
'author_name' => null,
],
]);
}
Expand Down