Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

I just repeated myself in api resource how to DRY

    public function toArray($request)
    {
        return [
            'name'          => $this->name,

            'profile'       => $this->when($request->fullUrl() == route('api.user.show',[$this->id,$this->slug]), $this->profile),

            'path'          => $this->path(),

            'image' => $this->when($request->fullUrl() == route('api.user.show',[$this->id,$this->slug]), $this->profile)
        ];
    }

I have one api resource and want to use it in different routes, The problem is i dont want to show some attributes in specific route, i used when method for this and it work but i think i repeated my self, How to clean this mess? Should i create new resource But if i do that is it ok that i have 2 resource for one model ?

0 likes
2 replies
Sinnbeck's avatar

I have multiple resources and it makes things so much cleaner as my resources isnt littered with if's and such. I know exactly what to expect when using a specific resource.

1 like
Jaytee's avatar

The more explicit you are with your response data, the better the consistency and development flow. Stick with @sinnbeck 's suggestion

You don't always need to conform to DRY, it's just a guideline. Sometimes it makes sense to do the opposite, especially when designing API responses.

1 like

Please or to participate in this conversation.