Closed boryn closed 3 years ago
@bpuig how are you? :) I bet quite busy?
Hello! I'm alive 😝 , but in summer I'm kinda out, I have a kid (now without school to attend, so more family time) and also vacations are coming. So development will be slow until summer ends and school starts again 😄
Hi! The same here :) Now the two kids go the grandparents, hoping to catch up with some things :) Disfruta tus vacaciones!
I think this is bloating a bit the Model, maybe you should take a look into https://laravel.com/docs/8.x/eloquent-resources
Resources are a layer between the model and the response, the place where you can include all that attributes. There they can even be conditional, functions, etc. Very flexible. I use them always in my API's. I think packages should not return this kind of resources, they should be made by the package users adapted to their needs.
See this example of the resource, including (part of) your attributes:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubscriptionResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'tag' => $this->tag,
'subscriber_type' => $this->subscriber_type,
'subscriber_id' => $this->subscriber_id,
'name' => $this->name,
'plan_id' => $this->plan_id,
'description' => $this->description,
'price' => $this->price,
'currency' => $this->currency,
'invoice_period' => $this->invoice_period,
'invoice_interval' => $this->invoice_interval,
'tier' => $this->tier,
'trial_ends_at' => $this->trial_ends_at,
'starts_at' => $this->starts_at,
'ends_at' => $this->ends_at,
'cancels_at' => $this->cancels_at,
'canceled_at' => $this->canceled_at,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'deleted_at' => $this->deleted_at,
'is_altered' => (bool) $this->isAltered(),
'is_active' => (bool) $this->isActive(),
'is_on_trial' => (bool) $this->isOnTrial(),
'plan' => Plan::make($this->whenLoaded('plan'))
];
}
}
Yes, that's true. It'd be much better to use eloquent resources.
Recently I was playing with GraphQL and Lighthouse (https://lighthouse-php.com), here is the way to have these extra attributes available if anyone needs it:
is_active: Boolean! @method(name: "isActive")
is_on_trial: Boolean! @method(name: "isOnTrial")
is_canceled: Boolean! @method(name: "isCanceled")
has_ended: Boolean! @method(name: "hasEnded")
is_altered: Boolean! @method(name: "isAltered")
Status
READY
Migrations
NO
Description
Implementation of the subscription status attributes:
as model accessors, so that they are available in
->toArray()
and->toJson()
. From a practical point of view it's very useful if you need to pass the subscription to the frontend through$this->response->json($subscription);
.