Blog

CakePHP

Generating a downloadable CSV file in CakePHP seems to be a bit of a stumbling block for many relatively new to using Cake. It doesn’t need to be challenging. There’s just a few basic steps you need to put in place.

As an example we’ll consider a Subscriber model that contains contact details of people who have subscribed to our app. We want to create a CSV export of all the subscribers data.

When using CakePHP’s (v2.x) saveAll method on a model you may have found that the afterSave callback for the model isn’t being called after everything has saved. Instead it is called just after the primary model is saved and before saving the associated model data. This can be a bit of a problem if you want to play around with the data from the associated models being saved in the saveAll. The way to get around this is to extend the saveAll method and create a new callback, afterSaveAll.