0

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?

0

1 Answer 1

1

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 .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.