So, how do we initiate Datatables when we don’t know what the data will look like beforehand?
Setting up Dynamic Headers for jQuery Datatables
We solved this by performing an initial server request to the database before we actually initialized the Datatable. This initial call simply performed a query to determine what the header values would be and returned them to the javascript in array format. This can either be stored in a different table or aggregated from a single table. How you store this data is out of scope for the article though, so I will move on.
Now that we had an array of the dynamic headers we could create our table and column definitions. The table was built using simple jQuery append methods as we had the tables scaffolding already created in our HTML. It looked something like this:

We had some default columns that needed to be included in the table, but once we had the dynamic values from the database we simply appended them to the row. One thing to note is that we appended the headers to the table before Datatables was ever initialized.
As I mentioned before, the array of values that we retrieved was also used to build the column definitions that Datatables requires to build the table. The function that we used to build out the column definitions looks something like this:

The function that we built for this task is a little more complicated because we had a few of the required columns that we needed to account for. In a situation where all the columns are dynamic, simply looping through the array and creating the objects that Datatables requires for its definitions does the trick.
Now that we had all the definitions defined and a table built, we needed to initialize Datatables. This requires some back-end work so let’s take a look at the Laravel-Datatables functions that we used.
Note: To use this, make sure to turn server-side processing on when initializing Datatables.