Efficiently handling large Eloquent results in Laravel

We sometimes need to handle large results of models when working with Eloquent. If we use the regular method of retrieving the full result set and working with the models, then it’s going to overflow our memory – essentially failing the entire process.

In order to bring efficiency to that process, we can lazy load the models in chunks and process them. Laravel provides two methods for that: lazy() and lazyById().

Consider a scenario where in a console command, we need to update a course’s average rating (example from Laravel Courses). Here’s how we can do that using the lazy() method, where courses will be fetched in chunks, and we can work with each of the retrieved models individually:

use App\Models\Course;
 
foreach (Course::lazy() as $course) {
$course->updateAverageRating();
}

Consider another use case where we want to perform bulk updates to a model but want to do that in chunks. Let’s see how that can be achieved:

use App\Models\Invoice;
 
Invoice::where('status', 'pending')
->lazyById(100)
->each->update(['status' => 'abandoned']);

The official documentation also has some good examples you can look into as well.

Enterprise PHP

I presented this talk on the Soft Expo 2010 – the largest software fair in Bangladesh. The intention was to clear some of the misconception about PHP, the growth of PHP, how it can fit in the enterprise now, etc.

After these, I shed light on some topics that a company/developer should keep in mind in order to write good software in PHP. This was followed by live session on caching, mysql query optimization, use of Xdebug, etc.

So here goes the presentation:

And a big thanks to Ivo Jansch’s “PHP in the real wolrd” presentation, from where I took inspiration.

Cheers!

Changing the default controller naming convention in CodeIgniter

CodeIgniter is one of my favorite framework and I often use it for developing application quickly. Although it is very flexible in most cases, I find its naming convention to be strict. Many times I have faced this problem when my controller’s class name and a model/library’s class names are the same – a Fatal error is inevitable and I have to forcefully change the name of the conflicting class to something less desirable (say from Users to UsersModel). Today I wanted to end this problem.

So I extended the CI_Router core class and made change to the _validate_request method. Now I can name my controller classes in this fashion: UsersController and it resides on the file system as controllers/UsersController.php. If you’ve tried other established frameworks, you should notice that this naming convention is widely used. So, if you have the same need, then just download the MY_Router.php file and put it on your application/libraries folder. That’s it.

Here is how your controller would start:

[cc lang=’php’]
(more…)