Adding user-specific settings in Laravel

Adding user-specific settings in Laravel

Storing the settings in the database

Starting off with adding the new column to the users table, this simple migration does the trick:

Sprinkle some getters on the User

Now that we have a simple way to set a user’s settings, we need a simple way to get them as well.

  1. It feels very comfortable when using the @property doc blocks. Through them, we notify our IDE that, on every $user instance, we can access properties like $user->settings and $user->social_links, and they will return an array. The more you have of these doc blocks, the merrier.
  2. We add the 'settings' => 'array' pair to the $casts array so that we don't have to json_encode() and json_decode() all the time to access the settings. You can also use 'json' instead of 'array'.
  3. The setting() method is straightforward, it simply checks if we have a setting with a given name and returns it, otherwise, it returns the default value provided. One gotcha here is that if the setting exists, but has a null-ish value, this method will return that instead of the default fallback. We want that by the way, at least for now. Also, notice $this->settings ?? [], we need this check since the column could be null.
  4. The getSocialLinksAttribute() method will allow us to access it like $user->social_links, and it will return only the settings that are not null-ish. This is for easier access in the front-end or other places in code. From Laravel 9 and above, there's a better way to define Accessors and Mutators on your models, you should check it out, it's the new kid in the block.

Does this work with nested settings?

In closing, we didn’t go with a nested settings approach, something like this:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Geni Jaho

Geni Jaho

Full-stack web developer with a passion for software architecture and programming best practices.