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

brunitosessa's avatar

Laravel Api Resources

I'm having problems understanding API resources in laravel 5.8. Supose I have a model called "Bars", and an API resource called BarResource:

class BarResource extends JsonResource
{
    public function toArray($request)
        return [
            'id' => $this->id,
            'name' => $this->name, 
        ]
    }
}

Ok. That works fine. Now I need to pass to every call, if the bar is opened or not (I can easeily calculate that). Where should I put the function that check if the bar is opened or closed?

class BarResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name, 
            'is_opened' => ??????
        ]
    }
}

Thanks a lot!

0 likes
3 replies
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@brunitosessa it depends, if you will only need is_opened value in your JSON resource, then it's fine to leave it in BarResource class, otherwise if you will need to access this value in other places, then add an accessor/method in the model class.

Sinnbeck's avatar

@brunitosessa if the answer helped you please consider marking it as best answer to mark the thread as solved

Please or to participate in this conversation.