Reputation: 807
How Laravel reassigning $this
to the model given in Api resources and return the just method in the class technically?
Assume we have this:
new TeamResource(Team::first());
then, in the TeamResrouce
when we call $this
, its Team
model instnace.
and automatically it called toArray()
method in the TeamResource
class.
without any constructor in exact class, how?
Upvotes: 0
Views: 1641
Reputation: 17206
The toArray()
call as the toJson()
call on model instances is done in the laravel kernel and request pipeline. here is some code
Illuminate\Routing\Router
@ toResponse()
public static function toResponse($request, $response)
{
if ($response instanceof Responsable) {
$response = $response->toResponse($request);
}
if ($response instanceof PsrResponseInterface) {
$response = (new HttpFoundationFactory)->createResponse($response);
} elseif ($response instanceof Model && $response->wasRecentlyCreated) {
$response = new JsonResponse($response, 201);
} elseif (! $response instanceof SymfonyResponse &&
($response instanceof Arrayable ||
$response instanceof Jsonable ||
$response instanceof ArrayObject ||
$response instanceof JsonSerializable ||
is_array($response))) {
$response = new JsonResponse($response);
} elseif (! $response instanceof SymfonyResponse) {
$response = new Response($response);
}
if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
$response->setNotModified();
}
return $response->prepare($request);
}
Upvotes: 1
Reputation: 50491
Magic method (__get
):
public function __get($key)
{
return $this->resource->{$key};
}
The API Resource (Illuminate\Http\Resources\Json\JsonResource
) defines this method so you can access the underlying model's attributes by accessing properties on the resource itself.
$this->something === $this->resource->something;
Notice that we can access model properties directly from the
$this
variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Laravel 5.8 Docs - Eloquent - API Resources
Upvotes: 1
Reputation: 76
I see two possible things, one is I haven't really seen anyone use another class model to initialize a completely different class. Youre problem may be in that way you initialize.
As well you could try assigning $this = TeamsResource(Team::first())
Upvotes: 0