This code will export both the column headers as well as the data in the csv format and return the result.

Finally, we need to add a bit of extra code to our controller in order to return the CSV data to our user. Assuming your model and controller are named posts, add the following code to your posts controller: