Creating Reusable Attributes for Laravel Resource Responses

Rafa Rafael - Oct 12 '23 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player