Use toBase in Eloquent to Reduce Memory in Laravel

Sometimes we require to load a huge amount of data into memory. Such as all the models we have in the database.  That time in general practices we use in Laravel is to write the following code.

$users = User::all();

 

But it consumes a really high amount of memory to load all the records and prepare Laravel Model class objects. Sometimes we load them in chunks to save the memory, but in some use cases, chunking can not be the option.

In such cases, Laravel has a handy function toBase(). By calling this function it will fetch the data from the database but it will not prepare the Eloquent models, but will just give us raw data and help us to save a ton of memory.

So my final code will look something like this

$users = User::toBase()->get();

 

You can also clone collection using toBase method in Laravel.  Now i will create a collection of names and then clone it using the toBase method and then modify the resulting collection.

// Create a collection of names.
$names = collect([
    'Alice',
    'Bob',
    'Charlie',
]);

// Create an uppercase-variant collection of names.
$upperCaseNames = $names->toBase()->map(function ($name) {
   return mb_strtoupper($name); 
});

 

Read also : Chunk Laravel | Process Big Data with Laravel Chunk

 

You can test it now by installing Laravel debugger. Hope it can help you.