Back

Hey! Laravelians ❤️ Can You Tell Me?

Did you ever have worked on a very huge Laravel project with millions of dataset & how do you optimize your queries in such a project using Eloquent or Raw SQL?

2

512

You can certainly use Eloquent to query millions of records. However, my advice is not to use models for querying.

For example, instead of doing:

$posts = Post::whereHas('tags', function($query){
$query->whereIn('tag',['php','laravel']);
})->get();

use joins:

$posts = DB::table('posts')
->join('post_tag','posts.id','=','post_tag.post_id')
->join('tags','post_tag.tag_id','=','tags.id')
->whereIn('tags.tag',['php','laravel'])
->get('posts.*');

It's true that this way the result is not a collection of models, so you won't have access to accessors and model methods, but the query will be several orders of magnitude faster. When we're talking about hundreds of thousands or millions of records, this makes a difference.

Moreover, even when using Chunks or lazy collections, you'll still have significant savings in terms of memory and time because models won't be instantiated.

2

180