Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Laravel Eloquent model's to eager load by default

Tags:

php

laravel

Laravel's eloquent models are set to lazy load by default. The problem is that it makes a lot of query to the database and especially during high traffic, the laravel application crashes whereas a similar application build on Yii 1 has no issues.

After installing the Laravel's debug bar, the problem is too many queries being made on every page load. The next step is to query optimization. I have been using eager loading as directed in the Laravel's documentation but still too many queries.

I was wondering if there is a way to set Eloquent to only "Eager Load" in dev environment. That way when the page fails to load, identifying issue would be easier.

like image 794
elixir Avatar asked Nov 18 '15 18:11

elixir


2 Answers

You could set defaults relations to "eager load" directly on the models :

Class MyModel extends Model {   protected $with = ['relation']; } 
like image 94
Louis Carrese Avatar answered Oct 12 '22 00:10

Louis Carrese


The solution for high database load is Cache.

Caching properly could give you incredible performance during high traffic, because it reduces common database queries to zero, and redirect them to RAM ones, which are faster.

Enabling Route Caching will increase perfomance too:

php artisan route:cache 

EDIT:

As Fx32 points, you should make sure that you need Eloquent and wouldn't be better to make the same query directly to the DB, joining the tables you need and making a single query instead of a lot:

Cache is not a good solution as a fix for bad database querying. Eloquent is great, but often it's better to write proper queries with some joins. Don't just bash away at your DB and then throw all the results in a cache, as it will introduce new problems. If your use case is not a flat CRUD API, ActiveRecord patterns might not be the best solution anyway. If you carefully select and join results from the DB, and want to speed up retrieval of such items, caching can help.

like image 25
vpedrosa Avatar answered Oct 11 '22 23:10

vpedrosa