0
votes

Could you please suggest which option I should use for the following example.

I'm currently building an API to get Places, Place model contains User and Location models.

Relationships are set like that:

class Place extends Model
{
    protected $guarded = [];

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by', 'id');
    }

    public function location()
    {
        return $this->belongsTo(Location::class);
    }
}

Option 1: Lazy Loading:

public function getPlaces()
{
    return Place::all()->get();
}
class PlaceResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'createdBy' => (new UserResource($this->createdBy)),
            'location' => (new LocationResource($this->location)),
        ];
    }
}

Option 2: Eager Loading:

public function getPlaces()
{
    return Place::with([
        'createdBy',
        'location',
    ])
    ->get();
}
class PlaceResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'createdBy' => (new UserResource($this->createdBy)),
            'location' => (new LocationResource($this->location)),
        ];
    }
}

Logically thinking with the Eager Loading option data should loads quicker, right? I have tested both options for about 100 places but the loading time seems to be the same.

What's the right way (option to use) to load data quicker?

1

1 Answers

1
votes

It is better to Eager Load those relationships when dealing with a result set like that. Since you are iterating through each record in that result set and accessing the relationship this would cause a N+1 issue otherwise. Since it is 2 relationships being accessed it would be (N*2) + 1 .