Adding user-specific settings in Laravel

Adding user-specific settings in Laravel

Storing the settings in the database

Sprinkle some getters on the User

  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?




Full-stack web developer with a passion for software architecture and cloud computing.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A few PHP developers in a Java World

You Can Know More about MemoryFoam

How to monitor Kubernetes + Docker with Datadog for the Keep-Network project.

I helped host 40 coding events last year. Here’s what I learned.

How to Build Smart Online Store in Less Than 21 Days!

Kubernetes(minikube) on Windows using chocolaty

Micropython for Beginners

Guide for Kafka with Spring Boot

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 cloud computing.

More from Medium

Laravel Eloquent “findOr” Method

Do you know what is polymorphic in Laravel?

Laravel — Service Container

Setting up a Laravel Local Environment with Docker