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

samehdev's avatar

Appending the Attributes to the Model’s with just api ?

I have a medium-sized project, when using "$ appends" within Model, the site becomes slow due to the large number of data, as I do not need this option except when using the api. How can I set a condition if it is on api, and at the same time I have relationships also have $ appends Is there any idea for solving this problem?

Can I do anything about it with the scope or the micro?

When using the "$ appends" the query number is more than 3000, and without it the normal number is 28 for the web

my code :

				class Adpost extends Model implements HasMedia, Feedable, Viewable

                  {

                    /***

                               ****/
                    protected $appends = ['media_photo', 'media_video', 'adcat_name',
                    'count_like', 'count_view', 
                    'content_without_html', 'body','url_short'];

                   }
0 likes
2 replies
npispas's avatar
npispas
Best Answer
Level 2

@samehdev Hi, yes there is an easy way to do it. You can use eager loading in your controller like so:

Your Controller:

class ExampleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index()
    {
        return ExampleResource::collection(Example::all()->load('relation', 'anotherRelation'));
    }
}

Then you are going to need to define an Api Resource for your Model like the following:

class Example extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'unique_id' => $this->unique_id,
            'comments' => $this->comments,
            'owner_name' => $this->owner_name,
            'guest_count' => $this->guest_count,
            'room_count' => $this->room_count,
            'status' => $this->status,
            'total_amount' => $this->total_amount,
            'total_due' => $this->total_due,
            'currency' => $this->currency,
            'relation' => AnotherExampleResource::collection($this->whenLoaded('relation')),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at
        ];
    }
}

Notice the whenLoaded method in the response. This will conditionally load the relation of the model only if you have eager loaded it somewhere, in our case the controller's index method.

A reference may be found here: https://laravel.com/docs/8.x/eloquent-resources#introduction and here https://laravel.com/docs/8.x/eloquent-resources#conditional-relationships

1 like

Please or to participate in this conversation.