DEV Community

Cover image for Creating Reusable Attributes for Laravel Resource Responses
Rafa Rafael
Rafa Rafael

Posted on

1

Creating Reusable Attributes for Laravel Resource Responses

At times, you may find the need to consistently include a shared related resource across multiple or all resource responses. Redundantly defining them in each individual resource not only bloats the code but also results in unnecessary duplication.

Consider this scenario: You have SubjectResource, StudentResource, and ClassroomResource. Now, imagine you want every response from these resources to also include a TeacherResource.

So, how can you achieve this without code repetition? Laravel provides an elegant solution. The JsonResource class in Laravel has a method named with(). This method is typically employed to append top-level metadata to your resource response alongside the resource array. By leveraging this method, you can effortlessly integrate TeacherResource into every response.

The trick is to create a trait and override the method. Allow me to guide you through the process.

First, Create a WithTeacher trait.
Then, within that trait, the code would appear like below:

<?php

namespace App\Traits;

use App\Http\Resources\TeacherResource;

trait WithTeacher
{
    public function with(Request $request): array
    {
        return [
            'teacher' => TeacherResource::make($this->resource)
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, to integrate this in your resources, simply incorporate use WithTeacher within the respective class.

<?php

namespace App\Http\Resources;

use App\Traits\WithTeacher;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class StudentResource extends JsonResource
{
    use WithTeacher;

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        //...
    }


}
Enter fullscreen mode Exit fullscreen mode

And Voilà! With this approach, should you ever need to include another related resource in the future, it'll be a breeze to add.

Enjoy!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
emmysteven profile image
Emmy Steven

Great Article, please keep it up

Collapse
 
rafaelogic profile image
Rafa Rafael

Thank you for the kind words! I'm glad you found it informative.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay