just like with any ORM that issues SQL queries for you, with Eloquent you can sometimes shoot yourself in the foot if you do not understand what it does behind the scene. For this reason, we will start by looking at a couple of things to consider improving the overall performance of your application. Lets take Example of cats variable

Eager loading records

When displaying several records that have one or more foreign key relationships, Eloquent will execute a new SQL query to resolve the related records every single time. This means that if you have 10 cats in your database and you want to display their breed, which is stored as a foreign key, there will be 10+1 database queries. This is referred as an n+1 problem; the first query retrieves the record and the n others go and find the related records. As n or the number of related fields increase, the impact on the performance of the application will become more noticeable.

To avoid this, make sure you tell Laravel the relations it should preload by using the with method:

Cat::with('breed', 'owner')->get();

This will perform a first query to load all cats and then perform only two more queries to retrieve the owners and breeds. If you were displaying 50 cats per page, for example, eager loading would bring the total number of SQL queries down from 101 to 3

Selecting only what you need

If you are working with large datasets or tables with many columns, you should avoid loading the values of all columns into memory. To only select the columns you need, pass an array to the get method in your query:


This query will simply turn into a SELECT name FROM cats SQL statemen