Best performance tricks to boost your laravel app

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.

Recommended :  The beginners guide to Pagination in laravel 5.2

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:

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares