How to make WordPress-like custom fields for Laravel models · vanrossum.dev    

       vanrossum.dev 

 Article

How to make WordPress-like custom fields for Laravel models
===========================================================

 ![](https://vanrossum.dev/images/jeffrey-portrait.webp) By Jeffrey van Rossum

  vanrossum.dev  

  [      vanrossum.dev ](https://vanrossum.dev)                      

  [ ← Writing ](https://vanrossum.dev/posts)   [ ← Writing ](https://vanrossum.dev/posts) [ Add one additional column ](#add-one-additional-column) [ Using a separate table ](#using-a-separate-table) [ Conclusion ](#conclusion) 

Have you ever run into a situation where you want to be able to dynamically store data along with your Laravel Model, without having to add an (excessive) amount of columns to your database table? I sure have.

I think there are a couple of ways to prevent your table from becoming massive in terms of columns. For example, WordPress uses something called [Custom Fields](https://wordpress.org/support/article/custom-fields/). With custom fields, you can dynamically store data along with your `WP_Post` objects. Those custom fields are stored in a separate database table.

Let's see how we could achieve something like that for Laravel. At this moment, I can think of two ways:

- Adding one additional column to our model's table and store our fields there as a json object
- Adding a separate database table for our custom fields (like WordPress)

We will take a look at both approaches. In both cases we are using a `Trait`. That will keep our `Model` clean and makes it easily reusable. Like this:

```php
class Article extends Model
{
    use HasMeta;
}

```

Add one additional column
-------------------------

For this example, the additional column will be called `meta` . You'll have to add this column to the table that you would want to support custom fields. Make sure to make it of the type `JSON` or `TEXT`.

Let's make it a `Trait`. In the below example I've created the `Trait` within the `App\Traits` namespace.

```php
