2 Common Mistakes I Make When Eager Loading in Laravel

Tram Ho

1. What is eager loading?

Laravel is one of the most popular php frameworks today, loved and used by the php developer community.

Query Performance is a topic that many of you may not be interested in when you first approach, but it is a very important issue in the system.

When we use Eloquent Relationships in laravel, it will default to “lazy” when loaded onto all model relationship (relation), brothers or problem encountered is N + 1 query.

Eager Loading will help shorten the queries in database manipulation to solve this problem, but during use, there are often errors related to it, here I would like to share with you. Common errors offline:

  • ID OMMISION
  • WHITE SPACING

2. ID OMMISION

To solve the lazy loading problem, we usually use the with () method as follows:

The above declaration will load all columns of the associated relationship . But if you want to Load each column of name, normally as we use it:

The problem is that it will not get the name column of the Company, to fix this, you have to add an id to it as follows:

To load specific columns in relationship , you must pass an additional ID for it!

3. WHITE SPACING

When you add a space before the name column is treated as part of the name and therefore when Laravel tries to load your query, it returns an error telling you that the column doesn’t exist. You will have a hard time noticing this because whitespace will most likely not happen to you in your error message.

4. Conclude

Eager Loading has made it very easy to build powerful web applications with Laravel.

If you are new to it or want to read more, visit the official documentation here officail docs

By the way I share with you a very nice package about helping to monitor our queries during application development, announcing when to add Eager Loading (when N + 1 query is present ) that is Laravel Query. Detector , you can install it and grab your project!

Sincerely, gossip, win!

Share the news now

Source : Viblo