mercredi 20 juin 2018

How do I convert an API resource class in Laravel 5.5 to an array BEFORE returning from controller?

Ordinarily, in Laravel 5.5, when using an api resource class, you simply return the resource class instance from your controller method, like so:

public function show(Request $request, MyModel $model)
{
    return new MyModelResource($model);
}

This converts the model to an array (and ultimately to json) in the response to the client.

However... I am trying to figure out how to convert everything to an array BEFORE returning it from the controller method. I tried this:

public function show(Request $request, MyModel $model)
{
    $array = (new MyModelResource($model))->toArray($request);

    // ...
}

The problem here is that any relationships loaded on the resource aren't also converted to an array. They show up inside $array as an instance of a resource class. Obviously calling toArray() manually does not result in a recursive call, and methods such as ->whenLoaded('relationship_name') aren't really respected either.

So how do I get Laravel to do everything it does to convert the resource to an array recursively WITHOUT having to return it from my controller method?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Ibebwa
via IFTTT

Aucun commentaire:

Enregistrer un commentaire