Home / Blog /

Decrease memory usage with the toBase() function

3 years ago

Decrease memory usage with the toBase() function

Laravel offers a lot of convenient functions. Using an ORM like Eloquent, a function like BlogPost::all(), not only fetches all blog posts from the database, but also prepares them as Models. This is very convenient if you need to have access to model functions. But what if you do not require these model functions, how can we decrease memory usage and improve performance?

👀 384 views

Laravel offers a nice function call toBase(), which can be called statically on your model.

BlogPost::all();

Which would return all the blog posts in the DB as a collection of prepared models. When performance is an issue and models do not have to prepared, use the following:

BlogPost::toBase()->get();

Which will return the blog posts as an array, where each blog post is a separate index of that array. For a large quantity of data, your memory usage will decrease and performance will be improved drastically.